babylon.max.js 3.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688
  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 MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. /**
  64. * Returns the log2 of value.
  65. */
  66. MathTools.Log2 = function (value) {
  67. return Math.log(value) * Math.LOG2E;
  68. };
  69. /**
  70. * Loops the value, so that it is never larger than length and never smaller than 0.
  71. *
  72. * This is similar to the modulo operator but it works with floating point numbers.
  73. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  74. * With t = 5 and length = 2.5, the result would be 0.0.
  75. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  76. */
  77. MathTools.Repeat = function (value, length) {
  78. return value - Math.floor(value / length) * length;
  79. };
  80. return MathTools;
  81. }());
  82. BABYLON.MathTools = MathTools;
  83. var Scalar = (function () {
  84. function Scalar() {
  85. }
  86. /**
  87. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  88. */
  89. Scalar.Lerp = function (start, end, amount) {
  90. return start + ((end - start) * amount);
  91. };
  92. /**
  93. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  94. */
  95. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  96. var squared = amount * amount;
  97. var cubed = amount * squared;
  98. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  99. var part2 = (-2.0 * cubed) + (3.0 * squared);
  100. var part3 = (cubed - (2.0 * squared)) + amount;
  101. var part4 = cubed - squared;
  102. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  103. };
  104. return Scalar;
  105. }());
  106. BABYLON.Scalar = Scalar;
  107. var Color3 = (function () {
  108. /**
  109. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  110. */
  111. function Color3(r, g, b) {
  112. if (r === void 0) { r = 0; }
  113. if (g === void 0) { g = 0; }
  114. if (b === void 0) { b = 0; }
  115. this.r = r;
  116. this.g = g;
  117. this.b = b;
  118. }
  119. /**
  120. * Returns a string with the Color3 current values.
  121. */
  122. Color3.prototype.toString = function () {
  123. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  124. };
  125. /**
  126. * Returns the string "Color3".
  127. */
  128. Color3.prototype.getClassName = function () {
  129. return "Color3";
  130. };
  131. /**
  132. * Returns the Color3 hash code.
  133. */
  134. Color3.prototype.getHashCode = function () {
  135. var hash = this.r || 0;
  136. hash = (hash * 397) ^ (this.g || 0);
  137. hash = (hash * 397) ^ (this.b || 0);
  138. return hash;
  139. };
  140. // Operators
  141. /**
  142. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  143. * Returns the Color3.
  144. */
  145. Color3.prototype.toArray = function (array, index) {
  146. if (index === undefined) {
  147. index = 0;
  148. }
  149. array[index] = this.r;
  150. array[index + 1] = this.g;
  151. array[index + 2] = this.b;
  152. return this;
  153. };
  154. /**
  155. * Returns a new Color4 object from the current Color3 and the passed alpha.
  156. */
  157. Color3.prototype.toColor4 = function (alpha) {
  158. if (alpha === void 0) { alpha = 1; }
  159. return new Color4(this.r, this.g, this.b, alpha);
  160. };
  161. /**
  162. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  163. */
  164. Color3.prototype.asArray = function () {
  165. var result = [];
  166. this.toArray(result, 0);
  167. return result;
  168. };
  169. /**
  170. * Returns the luminance value (float).
  171. */
  172. Color3.prototype.toLuminance = function () {
  173. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  174. };
  175. /**
  176. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  177. * Returns this new object.
  178. */
  179. Color3.prototype.multiply = function (otherColor) {
  180. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  181. };
  182. /**
  183. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  184. * Returns the current Color3.
  185. */
  186. Color3.prototype.multiplyToRef = function (otherColor, result) {
  187. result.r = this.r * otherColor.r;
  188. result.g = this.g * otherColor.g;
  189. result.b = this.b * otherColor.b;
  190. return this;
  191. };
  192. /**
  193. * Boolean : True if the rgb values are equal to the passed ones.
  194. */
  195. Color3.prototype.equals = function (otherColor) {
  196. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  197. };
  198. /**
  199. * Boolean : True if the rgb values are equal to the passed ones.
  200. */
  201. Color3.prototype.equalsFloats = function (r, g, b) {
  202. return this.r === r && this.g === g && this.b === b;
  203. };
  204. /**
  205. * Multiplies in place each rgb value by scale.
  206. * Returns the updated Color3.
  207. */
  208. Color3.prototype.scale = function (scale) {
  209. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  210. };
  211. /**
  212. * Multiplies the rgb values by scale and stores the result into "result".
  213. * Returns the unmodified current Color3.
  214. */
  215. Color3.prototype.scaleToRef = function (scale, result) {
  216. result.r = this.r * scale;
  217. result.g = this.g * scale;
  218. result.b = this.b * scale;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  223. */
  224. Color3.prototype.add = function (otherColor) {
  225. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  226. };
  227. /**
  228. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  229. * Returns the unmodified current Color3.
  230. */
  231. Color3.prototype.addToRef = function (otherColor, result) {
  232. result.r = this.r + otherColor.r;
  233. result.g = this.g + otherColor.g;
  234. result.b = this.b + otherColor.b;
  235. return this;
  236. };
  237. /**
  238. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  239. */
  240. Color3.prototype.subtract = function (otherColor) {
  241. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  242. };
  243. /**
  244. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  245. * Returns the unmodified current Color3.
  246. */
  247. Color3.prototype.subtractToRef = function (otherColor, result) {
  248. result.r = this.r - otherColor.r;
  249. result.g = this.g - otherColor.g;
  250. result.b = this.b - otherColor.b;
  251. return this;
  252. };
  253. /**
  254. * Returns a new Color3 copied the current one.
  255. */
  256. Color3.prototype.clone = function () {
  257. return new Color3(this.r, this.g, this.b);
  258. };
  259. /**
  260. * Copies the rgb values from the source in the current Color3.
  261. * Returns the updated Color3.
  262. */
  263. Color3.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. return this;
  268. };
  269. /**
  270. * Updates the Color3 rgb values from the passed floats.
  271. * Returns the Color3.
  272. */
  273. Color3.prototype.copyFromFloats = function (r, g, b) {
  274. this.r = r;
  275. this.g = g;
  276. this.b = b;
  277. return this;
  278. };
  279. /**
  280. * Updates the Color3 rgb values from the passed floats.
  281. * Returns the Color3.
  282. */
  283. Color3.prototype.set = function (r, g, b) {
  284. return this.copyFromFloats(r, g, b);
  285. };
  286. /**
  287. * Returns the Color3 hexadecimal code as a string.
  288. */
  289. Color3.prototype.toHexString = function () {
  290. var intR = (this.r * 255) | 0;
  291. var intG = (this.g * 255) | 0;
  292. var intB = (this.b * 255) | 0;
  293. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  294. };
  295. /**
  296. * Returns a new Color3 converted to linear space.
  297. */
  298. Color3.prototype.toLinearSpace = function () {
  299. var convertedColor = new Color3();
  300. this.toLinearSpaceToRef(convertedColor);
  301. return convertedColor;
  302. };
  303. /**
  304. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  305. * Returns the unmodified Color3.
  306. */
  307. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  308. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  309. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  310. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  311. return this;
  312. };
  313. /**
  314. * Returns a new Color3 converted to gamma space.
  315. */
  316. Color3.prototype.toGammaSpace = function () {
  317. var convertedColor = new Color3();
  318. this.toGammaSpaceToRef(convertedColor);
  319. return convertedColor;
  320. };
  321. /**
  322. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  323. * Returns the unmodified Color3.
  324. */
  325. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  326. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  327. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  328. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  329. return this;
  330. };
  331. // Statics
  332. /**
  333. * Creates a new Color3 from the string containing valid hexadecimal values.
  334. */
  335. Color3.FromHexString = function (hex) {
  336. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  337. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  338. return new Color3(0, 0, 0);
  339. }
  340. var r = parseInt(hex.substring(1, 3), 16);
  341. var g = parseInt(hex.substring(3, 5), 16);
  342. var b = parseInt(hex.substring(5, 7), 16);
  343. return Color3.FromInts(r, g, b);
  344. };
  345. /**
  346. * Creates a new Vector3 from the startind index of the passed array.
  347. */
  348. Color3.FromArray = function (array, offset) {
  349. if (offset === void 0) { offset = 0; }
  350. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  351. };
  352. /**
  353. * Creates a new Color3 from integer values ( < 256).
  354. */
  355. Color3.FromInts = function (r, g, b) {
  356. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  357. };
  358. /**
  359. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  360. */
  361. Color3.Lerp = function (start, end, amount) {
  362. var r = start.r + ((end.r - start.r) * amount);
  363. var g = start.g + ((end.g - start.g) * amount);
  364. var b = start.b + ((end.b - start.b) * amount);
  365. return new Color3(r, g, b);
  366. };
  367. Color3.Red = function () { return new Color3(1, 0, 0); };
  368. Color3.Green = function () { return new Color3(0, 1, 0); };
  369. Color3.Blue = function () { return new Color3(0, 0, 1); };
  370. Color3.Black = function () { return new Color3(0, 0, 0); };
  371. Color3.White = function () { return new Color3(1, 1, 1); };
  372. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  373. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  374. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  375. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  376. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  377. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  378. return Color3;
  379. }());
  380. BABYLON.Color3 = Color3;
  381. var Color4 = (function () {
  382. /**
  383. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  384. */
  385. function Color4(r, g, b, a) {
  386. if (r === void 0) { r = 0; }
  387. if (g === void 0) { g = 0; }
  388. if (b === void 0) { b = 0; }
  389. if (a === void 0) { a = 1; }
  390. this.r = r;
  391. this.g = g;
  392. this.b = b;
  393. this.a = a;
  394. }
  395. // Operators
  396. /**
  397. * Adds in place the passed Color4 values to the current Color4.
  398. * Returns the updated Color4.
  399. */
  400. Color4.prototype.addInPlace = function (right) {
  401. this.r += right.r;
  402. this.g += right.g;
  403. this.b += right.b;
  404. this.a += right.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  409. */
  410. Color4.prototype.asArray = function () {
  411. var result = [];
  412. this.toArray(result, 0);
  413. return result;
  414. };
  415. /**
  416. * Stores from the starting index in the passed array the Color4 successive values.
  417. * Returns the Color4.
  418. */
  419. Color4.prototype.toArray = function (array, index) {
  420. if (index === undefined) {
  421. index = 0;
  422. }
  423. array[index] = this.r;
  424. array[index + 1] = this.g;
  425. array[index + 2] = this.b;
  426. array[index + 3] = this.a;
  427. return this;
  428. };
  429. /**
  430. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  431. */
  432. Color4.prototype.add = function (right) {
  433. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  434. };
  435. /**
  436. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  437. */
  438. Color4.prototype.subtract = function (right) {
  439. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  440. };
  441. /**
  442. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  443. * Returns the Color4.
  444. */
  445. Color4.prototype.subtractToRef = function (right, result) {
  446. result.r = this.r - right.r;
  447. result.g = this.g - right.g;
  448. result.b = this.b - right.b;
  449. result.a = this.a - right.a;
  450. return this;
  451. };
  452. /**
  453. * Creates a new Color4 with the current Color4 values multiplied by scale.
  454. */
  455. Color4.prototype.scale = function (scale) {
  456. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  457. };
  458. /**
  459. * Multiplies the current Color4 values by scale and stores the result in "result".
  460. * Returns the Color4.
  461. */
  462. Color4.prototype.scaleToRef = function (scale, result) {
  463. result.r = this.r * scale;
  464. result.g = this.g * scale;
  465. result.b = this.b * scale;
  466. result.a = this.a * scale;
  467. return this;
  468. };
  469. /**
  470. * Multipy an RGBA Color4 value by another and return a new Color4 object
  471. * @param color The Color4 (RGBA) value to multiply by
  472. * @returns A new Color4.
  473. */
  474. Color4.prototype.multiply = function (color) {
  475. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  476. };
  477. /**
  478. * Multipy an RGBA Color4 value by another and push the result in a reference value
  479. * @param color The Color4 (RGBA) value to multiply by
  480. * @param result The Color4 (RGBA) to fill the result in
  481. * @returns the result Color4.
  482. */
  483. Color4.prototype.multiplyToRef = function (color, result) {
  484. result.r = this.r * color.r;
  485. result.g = this.g * color.g;
  486. result.b = this.b * color.b;
  487. result.a = this.a * color.a;
  488. return result;
  489. };
  490. /**
  491. * Returns a string with the Color4 values.
  492. */
  493. Color4.prototype.toString = function () {
  494. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  495. };
  496. /**
  497. * Returns the string "Color4"
  498. */
  499. Color4.prototype.getClassName = function () {
  500. return "Color4";
  501. };
  502. /**
  503. * Return the Color4 hash code as a number.
  504. */
  505. Color4.prototype.getHashCode = function () {
  506. var hash = this.r || 0;
  507. hash = (hash * 397) ^ (this.g || 0);
  508. hash = (hash * 397) ^ (this.b || 0);
  509. hash = (hash * 397) ^ (this.a || 0);
  510. return hash;
  511. };
  512. /**
  513. * Creates a new Color4 copied from the current one.
  514. */
  515. Color4.prototype.clone = function () {
  516. return new Color4(this.r, this.g, this.b, this.a);
  517. };
  518. /**
  519. * Copies the passed Color4 values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.copyFrom = function (source) {
  523. this.r = source.r;
  524. this.g = source.g;
  525. this.b = source.b;
  526. this.a = source.a;
  527. return this;
  528. };
  529. /**
  530. * Copies the passed float values into the current one.
  531. * Returns the updated Color4.
  532. */
  533. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  534. this.r = r;
  535. this.g = g;
  536. this.b = b;
  537. this.a = a;
  538. return this;
  539. };
  540. /**
  541. * Copies the passed float values into the current one.
  542. * Returns the updated Color4.
  543. */
  544. Color4.prototype.set = function (r, g, b, a) {
  545. return this.copyFromFloats(r, g, b, a);
  546. };
  547. /**
  548. * Returns a string containing the hexadecimal Color4 code.
  549. */
  550. Color4.prototype.toHexString = function () {
  551. var intR = (this.r * 255) | 0;
  552. var intG = (this.g * 255) | 0;
  553. var intB = (this.b * 255) | 0;
  554. var intA = (this.a * 255) | 0;
  555. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  556. };
  557. /**
  558. * Returns a new Color4 converted to linear space.
  559. */
  560. Color4.prototype.toLinearSpace = function () {
  561. var convertedColor = new Color4();
  562. this.toLinearSpaceToRef(convertedColor);
  563. return convertedColor;
  564. };
  565. /**
  566. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  567. * Returns the unmodified Color4.
  568. */
  569. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  570. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  571. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  572. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  573. convertedColor.a = this.a;
  574. return this;
  575. };
  576. /**
  577. * Returns a new Color4 converted to gamma space.
  578. */
  579. Color4.prototype.toGammaSpace = function () {
  580. var convertedColor = new Color4();
  581. this.toGammaSpaceToRef(convertedColor);
  582. return convertedColor;
  583. };
  584. /**
  585. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  586. * Returns the unmodified Color4.
  587. */
  588. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  589. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  590. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  591. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  592. convertedColor.a = this.a;
  593. return this;
  594. };
  595. // Statics
  596. /**
  597. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  598. */
  599. Color4.FromHexString = function (hex) {
  600. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  601. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  602. return new Color4(0.0, 0.0, 0.0, 0.0);
  603. }
  604. var r = parseInt(hex.substring(1, 3), 16);
  605. var g = parseInt(hex.substring(3, 5), 16);
  606. var b = parseInt(hex.substring(5, 7), 16);
  607. var a = parseInt(hex.substring(7, 9), 16);
  608. return Color4.FromInts(r, g, b, a);
  609. };
  610. /**
  611. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  612. */
  613. Color4.Lerp = function (left, right, amount) {
  614. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  615. Color4.LerpToRef(left, right, amount, result);
  616. return result;
  617. };
  618. /**
  619. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  620. */
  621. Color4.LerpToRef = function (left, right, amount, result) {
  622. result.r = left.r + (right.r - left.r) * amount;
  623. result.g = left.g + (right.g - left.g) * amount;
  624. result.b = left.b + (right.b - left.b) * amount;
  625. result.a = left.a + (right.a - left.a) * amount;
  626. };
  627. /**
  628. * Creates a new Color4 from the starting index element of the passed array.
  629. */
  630. Color4.FromArray = function (array, offset) {
  631. if (offset === void 0) { offset = 0; }
  632. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  633. };
  634. /**
  635. * Creates a new Color4 from the passed integers ( < 256 ).
  636. */
  637. Color4.FromInts = function (r, g, b, a) {
  638. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  639. };
  640. Color4.CheckColors4 = function (colors, count) {
  641. // Check if color3 was used
  642. if (colors.length === count * 3) {
  643. var colors4 = [];
  644. for (var index = 0; index < colors.length; index += 3) {
  645. var newIndex = (index / 3) * 4;
  646. colors4[newIndex] = colors[index];
  647. colors4[newIndex + 1] = colors[index + 1];
  648. colors4[newIndex + 2] = colors[index + 2];
  649. colors4[newIndex + 3] = 1.0;
  650. }
  651. return colors4;
  652. }
  653. return colors;
  654. };
  655. return Color4;
  656. }());
  657. BABYLON.Color4 = Color4;
  658. var Vector2 = (function () {
  659. /**
  660. * Creates a new Vector2 from the passed x and y coordinates.
  661. */
  662. function Vector2(x, y) {
  663. this.x = x;
  664. this.y = y;
  665. }
  666. /**
  667. * Returns a string with the Vector2 coordinates.
  668. */
  669. Vector2.prototype.toString = function () {
  670. return "{X: " + this.x + " Y:" + this.y + "}";
  671. };
  672. /**
  673. * Returns the string "Vector2"
  674. */
  675. Vector2.prototype.getClassName = function () {
  676. return "Vector2";
  677. };
  678. /**
  679. * Returns the Vector2 hash code as a number.
  680. */
  681. Vector2.prototype.getHashCode = function () {
  682. var hash = this.x || 0;
  683. hash = (hash * 397) ^ (this.y || 0);
  684. return hash;
  685. };
  686. // Operators
  687. /**
  688. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  689. * Returns the Vector2.
  690. */
  691. Vector2.prototype.toArray = function (array, index) {
  692. if (index === void 0) { index = 0; }
  693. array[index] = this.x;
  694. array[index + 1] = this.y;
  695. return this;
  696. };
  697. /**
  698. * Returns a new array with 2 elements : the Vector2 coordinates.
  699. */
  700. Vector2.prototype.asArray = function () {
  701. var result = [];
  702. this.toArray(result, 0);
  703. return result;
  704. };
  705. /**
  706. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  707. * Returns the updated Vector2.
  708. */
  709. Vector2.prototype.copyFrom = function (source) {
  710. this.x = source.x;
  711. this.y = source.y;
  712. return this;
  713. };
  714. /**
  715. * Sets the Vector2 coordinates with the passed floats.
  716. * Returns the updated Vector2.
  717. */
  718. Vector2.prototype.copyFromFloats = function (x, y) {
  719. this.x = x;
  720. this.y = y;
  721. return this;
  722. };
  723. /**
  724. * Sets the Vector2 coordinates with the passed floats.
  725. * Returns the updated Vector2.
  726. */
  727. Vector2.prototype.set = function (x, y) {
  728. return this.copyFromFloats(x, y);
  729. };
  730. /**
  731. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  732. */
  733. Vector2.prototype.add = function (otherVector) {
  734. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  735. };
  736. /**
  737. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  738. * Returns the Vector2.
  739. */
  740. Vector2.prototype.addToRef = function (otherVector, result) {
  741. result.x = this.x + otherVector.x;
  742. result.y = this.y + otherVector.y;
  743. return this;
  744. };
  745. /**
  746. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  747. * Returns the updated Vector2.
  748. */
  749. Vector2.prototype.addInPlace = function (otherVector) {
  750. this.x += otherVector.x;
  751. this.y += otherVector.y;
  752. return this;
  753. };
  754. /**
  755. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  756. */
  757. Vector2.prototype.addVector3 = function (otherVector) {
  758. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  759. };
  760. /**
  761. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  762. */
  763. Vector2.prototype.subtract = function (otherVector) {
  764. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  765. };
  766. /**
  767. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  768. * Returns the Vector2.
  769. */
  770. Vector2.prototype.subtractToRef = function (otherVector, result) {
  771. result.x = this.x - otherVector.x;
  772. result.y = this.y - otherVector.y;
  773. return this;
  774. };
  775. /**
  776. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.subtractInPlace = function (otherVector) {
  780. this.x -= otherVector.x;
  781. this.y -= otherVector.y;
  782. return this;
  783. };
  784. /**
  785. * Multiplies in place the current Vector2 coordinates by the passed ones.
  786. * Returns the updated Vector2.
  787. */
  788. Vector2.prototype.multiplyInPlace = function (otherVector) {
  789. this.x *= otherVector.x;
  790. this.y *= otherVector.y;
  791. return this;
  792. };
  793. /**
  794. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  795. */
  796. Vector2.prototype.multiply = function (otherVector) {
  797. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  798. };
  799. /**
  800. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  801. * Returns the Vector2.
  802. */
  803. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  804. result.x = this.x * otherVector.x;
  805. result.y = this.y * otherVector.y;
  806. return this;
  807. };
  808. /**
  809. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  810. */
  811. Vector2.prototype.multiplyByFloats = function (x, y) {
  812. return new Vector2(this.x * x, this.y * y);
  813. };
  814. /**
  815. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  816. */
  817. Vector2.prototype.divide = function (otherVector) {
  818. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  819. };
  820. /**
  821. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  822. * Returns the Vector2.
  823. */
  824. Vector2.prototype.divideToRef = function (otherVector, result) {
  825. result.x = this.x / otherVector.x;
  826. result.y = this.y / otherVector.y;
  827. return this;
  828. };
  829. /**
  830. * Returns a new Vector2 with current Vector2 negated coordinates.
  831. */
  832. Vector2.prototype.negate = function () {
  833. return new Vector2(-this.x, -this.y);
  834. };
  835. /**
  836. * Multiply the Vector2 coordinates by scale.
  837. * Returns the updated Vector2.
  838. */
  839. Vector2.prototype.scaleInPlace = function (scale) {
  840. this.x *= scale;
  841. this.y *= scale;
  842. return this;
  843. };
  844. /**
  845. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  846. */
  847. Vector2.prototype.scale = function (scale) {
  848. return new Vector2(this.x * scale, this.y * scale);
  849. };
  850. /**
  851. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  852. */
  853. Vector2.prototype.equals = function (otherVector) {
  854. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  855. };
  856. /**
  857. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  858. */
  859. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  860. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  861. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  862. };
  863. // Properties
  864. /**
  865. * Returns the vector length (float).
  866. */
  867. Vector2.prototype.length = function () {
  868. return Math.sqrt(this.x * this.x + this.y * this.y);
  869. };
  870. /**
  871. * Returns the vector squared length (float);
  872. */
  873. Vector2.prototype.lengthSquared = function () {
  874. return (this.x * this.x + this.y * this.y);
  875. };
  876. // Methods
  877. /**
  878. * Normalize the vector.
  879. * Returns the updated Vector2.
  880. */
  881. Vector2.prototype.normalize = function () {
  882. var len = this.length();
  883. if (len === 0)
  884. return this;
  885. var num = 1.0 / len;
  886. this.x *= num;
  887. this.y *= num;
  888. return this;
  889. };
  890. /**
  891. * Returns a new Vector2 copied from the Vector2.
  892. */
  893. Vector2.prototype.clone = function () {
  894. return new Vector2(this.x, this.y);
  895. };
  896. // Statics
  897. /**
  898. * Returns a new Vector2(0, 0)
  899. */
  900. Vector2.Zero = function () {
  901. return new Vector2(0, 0);
  902. };
  903. /**
  904. * Returns a new Vector2(1, 1)
  905. */
  906. Vector2.One = function () {
  907. return new Vector2(1, 1);
  908. };
  909. /**
  910. * Returns a new Vector2 set from the passed index element of the passed array.
  911. */
  912. Vector2.FromArray = function (array, offset) {
  913. if (offset === void 0) { offset = 0; }
  914. return new Vector2(array[offset], array[offset + 1]);
  915. };
  916. /**
  917. * Sets "result" from the passed index element of the passed array.
  918. */
  919. Vector2.FromArrayToRef = function (array, offset, result) {
  920. result.x = array[offset];
  921. result.y = array[offset + 1];
  922. };
  923. /**
  924. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  925. */
  926. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  927. var squared = amount * amount;
  928. var cubed = amount * squared;
  929. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  930. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  931. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  932. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  933. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  934. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  935. return new Vector2(x, y);
  936. };
  937. /**
  938. * 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".
  939. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  940. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  941. */
  942. Vector2.Clamp = function (value, min, max) {
  943. var x = value.x;
  944. x = (x > max.x) ? max.x : x;
  945. x = (x < min.x) ? min.x : x;
  946. var y = value.y;
  947. y = (y > max.y) ? max.y : y;
  948. y = (y < min.y) ? min.y : y;
  949. return new Vector2(x, y);
  950. };
  951. /**
  952. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  953. */
  954. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  955. var squared = amount * amount;
  956. var cubed = amount * squared;
  957. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  958. var part2 = (-2.0 * cubed) + (3.0 * squared);
  959. var part3 = (cubed - (2.0 * squared)) + amount;
  960. var part4 = cubed - squared;
  961. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  962. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  963. return new Vector2(x, y);
  964. };
  965. /**
  966. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  967. */
  968. Vector2.Lerp = function (start, end, amount) {
  969. var x = start.x + ((end.x - start.x) * amount);
  970. var y = start.y + ((end.y - start.y) * amount);
  971. return new Vector2(x, y);
  972. };
  973. /**
  974. * Returns the dot product (float) of the vector "left" and the vector "right".
  975. */
  976. Vector2.Dot = function (left, right) {
  977. return left.x * right.x + left.y * right.y;
  978. };
  979. /**
  980. * Returns a new Vector2 equal to the normalized passed vector.
  981. */
  982. Vector2.Normalize = function (vector) {
  983. var newVector = vector.clone();
  984. newVector.normalize();
  985. return newVector;
  986. };
  987. /**
  988. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  989. */
  990. Vector2.Minimize = function (left, right) {
  991. var x = (left.x < right.x) ? left.x : right.x;
  992. var y = (left.y < right.y) ? left.y : right.y;
  993. return new Vector2(x, y);
  994. };
  995. /**
  996. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  997. */
  998. Vector2.Maximize = function (left, right) {
  999. var x = (left.x > right.x) ? left.x : right.x;
  1000. var y = (left.y > right.y) ? left.y : right.y;
  1001. return new Vector2(x, y);
  1002. };
  1003. /**
  1004. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1005. */
  1006. Vector2.Transform = function (vector, transformation) {
  1007. var r = Vector2.Zero();
  1008. Vector2.TransformToRef(vector, transformation, r);
  1009. return r;
  1010. };
  1011. /**
  1012. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1013. */
  1014. Vector2.TransformToRef = function (vector, transformation, result) {
  1015. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1016. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1017. result.x = x;
  1018. result.y = y;
  1019. };
  1020. /**
  1021. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1022. */
  1023. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1024. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1025. var sign = a < 0 ? -1 : 1;
  1026. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1027. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1028. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1029. };
  1030. /**
  1031. * Returns the distance (float) between the vectors "value1" and "value2".
  1032. */
  1033. Vector2.Distance = function (value1, value2) {
  1034. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1035. };
  1036. /**
  1037. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1038. */
  1039. Vector2.DistanceSquared = function (value1, value2) {
  1040. var x = value1.x - value2.x;
  1041. var y = value1.y - value2.y;
  1042. return (x * x) + (y * y);
  1043. };
  1044. /**
  1045. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1046. */
  1047. Vector2.Center = function (value1, value2) {
  1048. var center = value1.add(value2);
  1049. center.scaleInPlace(0.5);
  1050. return center;
  1051. };
  1052. /**
  1053. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1054. */
  1055. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1056. var l2 = Vector2.DistanceSquared(segA, segB);
  1057. if (l2 === 0.0) {
  1058. return Vector2.Distance(p, segA);
  1059. }
  1060. var v = segB.subtract(segA);
  1061. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1062. var proj = segA.add(v.multiplyByFloats(t, t));
  1063. return Vector2.Distance(p, proj);
  1064. };
  1065. return Vector2;
  1066. }());
  1067. BABYLON.Vector2 = Vector2;
  1068. var Vector3 = (function () {
  1069. /**
  1070. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1071. * A Vector3 is the main object used in 3D geometry.
  1072. * It can represent etiher the coordinates of a point the space, either a direction.
  1073. */
  1074. function Vector3(x, y, z) {
  1075. this.x = x;
  1076. this.y = y;
  1077. this.z = z;
  1078. }
  1079. /**
  1080. * Returns a string with the Vector3 coordinates.
  1081. */
  1082. Vector3.prototype.toString = function () {
  1083. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1084. };
  1085. /**
  1086. * Returns the string "Vector3"
  1087. */
  1088. Vector3.prototype.getClassName = function () {
  1089. return "Vector3";
  1090. };
  1091. /**
  1092. * Returns the Vector hash code.
  1093. */
  1094. Vector3.prototype.getHashCode = function () {
  1095. var hash = this.x || 0;
  1096. hash = (hash * 397) ^ (this.y || 0);
  1097. hash = (hash * 397) ^ (this.z || 0);
  1098. return hash;
  1099. };
  1100. // Operators
  1101. /**
  1102. * Returns a new array with three elements : the coordinates the Vector3.
  1103. */
  1104. Vector3.prototype.asArray = function () {
  1105. var result = [];
  1106. this.toArray(result, 0);
  1107. return result;
  1108. };
  1109. /**
  1110. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1111. * Returns the Vector3.
  1112. */
  1113. Vector3.prototype.toArray = function (array, index) {
  1114. if (index === void 0) { index = 0; }
  1115. array[index] = this.x;
  1116. array[index + 1] = this.y;
  1117. array[index + 2] = this.z;
  1118. return this;
  1119. };
  1120. /**
  1121. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1122. */
  1123. Vector3.prototype.toQuaternion = function () {
  1124. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1125. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1126. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1127. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1128. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1129. var cosy = Math.cos(this.y * 0.5);
  1130. var siny = Math.sin(this.y * 0.5);
  1131. result.x = coszMinusx * siny;
  1132. result.y = -sinzMinusx * siny;
  1133. result.z = sinxPlusz * cosy;
  1134. result.w = cosxPlusz * cosy;
  1135. return result;
  1136. };
  1137. /**
  1138. * Adds the passed vector to the current Vector3.
  1139. * Returns the updated Vector3.
  1140. */
  1141. Vector3.prototype.addInPlace = function (otherVector) {
  1142. this.x += otherVector.x;
  1143. this.y += otherVector.y;
  1144. this.z += otherVector.z;
  1145. return this;
  1146. };
  1147. /**
  1148. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1149. */
  1150. Vector3.prototype.add = function (otherVector) {
  1151. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1152. };
  1153. /**
  1154. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1155. * Returns the current Vector3.
  1156. */
  1157. Vector3.prototype.addToRef = function (otherVector, result) {
  1158. result.x = this.x + otherVector.x;
  1159. result.y = this.y + otherVector.y;
  1160. result.z = this.z + otherVector.z;
  1161. return this;
  1162. };
  1163. /**
  1164. * Subtract the passed vector from the current Vector3.
  1165. * Returns the updated Vector3.
  1166. */
  1167. Vector3.prototype.subtractInPlace = function (otherVector) {
  1168. this.x -= otherVector.x;
  1169. this.y -= otherVector.y;
  1170. this.z -= otherVector.z;
  1171. return this;
  1172. };
  1173. /**
  1174. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1175. */
  1176. Vector3.prototype.subtract = function (otherVector) {
  1177. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1178. };
  1179. /**
  1180. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1181. * Returns the current Vector3.
  1182. */
  1183. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1184. result.x = this.x - otherVector.x;
  1185. result.y = this.y - otherVector.y;
  1186. result.z = this.z - otherVector.z;
  1187. return this;
  1188. };
  1189. /**
  1190. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1191. */
  1192. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1193. return new Vector3(this.x - x, this.y - y, this.z - z);
  1194. };
  1195. /**
  1196. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1197. * Returns the current Vector3.
  1198. */
  1199. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1200. result.x = this.x - x;
  1201. result.y = this.y - y;
  1202. result.z = this.z - z;
  1203. return this;
  1204. };
  1205. /**
  1206. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1207. */
  1208. Vector3.prototype.negate = function () {
  1209. return new Vector3(-this.x, -this.y, -this.z);
  1210. };
  1211. /**
  1212. * Multiplies the Vector3 coordinates by the float "scale".
  1213. * Returns the updated Vector3.
  1214. */
  1215. Vector3.prototype.scaleInPlace = function (scale) {
  1216. this.x *= scale;
  1217. this.y *= scale;
  1218. this.z *= scale;
  1219. return this;
  1220. };
  1221. /**
  1222. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1223. */
  1224. Vector3.prototype.scale = function (scale) {
  1225. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1226. };
  1227. /**
  1228. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1229. * Returns the current Vector3.
  1230. */
  1231. Vector3.prototype.scaleToRef = function (scale, result) {
  1232. result.x = this.x * scale;
  1233. result.y = this.y * scale;
  1234. result.z = this.z * scale;
  1235. return this;
  1236. };
  1237. /**
  1238. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1239. */
  1240. Vector3.prototype.equals = function (otherVector) {
  1241. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1242. };
  1243. /**
  1244. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1245. */
  1246. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1247. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1248. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1249. };
  1250. /**
  1251. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1252. */
  1253. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1254. return this.x === x && this.y === y && this.z === z;
  1255. };
  1256. /**
  1257. * Muliplies the current Vector3 coordinates by the passed ones.
  1258. * Returns the updated Vector3.
  1259. */
  1260. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1261. this.x *= otherVector.x;
  1262. this.y *= otherVector.y;
  1263. this.z *= otherVector.z;
  1264. return this;
  1265. };
  1266. /**
  1267. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1268. */
  1269. Vector3.prototype.multiply = function (otherVector) {
  1270. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1271. };
  1272. /**
  1273. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1274. * Returns the current Vector3.
  1275. */
  1276. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1277. result.x = this.x * otherVector.x;
  1278. result.y = this.y * otherVector.y;
  1279. result.z = this.z * otherVector.z;
  1280. return this;
  1281. };
  1282. /**
  1283. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1284. */
  1285. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1286. return new Vector3(this.x * x, this.y * y, this.z * z);
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1290. */
  1291. Vector3.prototype.divide = function (otherVector) {
  1292. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1293. };
  1294. /**
  1295. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.divideToRef = function (otherVector, result) {
  1299. result.x = this.x / otherVector.x;
  1300. result.y = this.y / otherVector.y;
  1301. result.z = this.z / otherVector.z;
  1302. return this;
  1303. };
  1304. /**
  1305. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1306. * Returns the updated Vector3.
  1307. */
  1308. Vector3.prototype.MinimizeInPlace = function (other) {
  1309. if (other.x < this.x)
  1310. this.x = other.x;
  1311. if (other.y < this.y)
  1312. this.y = other.y;
  1313. if (other.z < this.z)
  1314. this.z = other.z;
  1315. return this;
  1316. };
  1317. /**
  1318. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1319. * Returns the updated Vector3.
  1320. */
  1321. Vector3.prototype.MaximizeInPlace = function (other) {
  1322. if (other.x > this.x)
  1323. this.x = other.x;
  1324. if (other.y > this.y)
  1325. this.y = other.y;
  1326. if (other.z > this.z)
  1327. this.z = other.z;
  1328. return this;
  1329. };
  1330. // Properties
  1331. /**
  1332. * Returns the length of the Vector3 (float).
  1333. */
  1334. Vector3.prototype.length = function () {
  1335. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1336. };
  1337. /**
  1338. * Returns the squared length of the Vector3 (float).
  1339. */
  1340. Vector3.prototype.lengthSquared = function () {
  1341. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1342. };
  1343. // Methods
  1344. /**
  1345. * Normalize the current Vector3.
  1346. * Returns the updated Vector3.
  1347. */
  1348. Vector3.prototype.normalize = function () {
  1349. var len = this.length();
  1350. if (len === 0 || len === 1.0)
  1351. return this;
  1352. var num = 1.0 / len;
  1353. this.x *= num;
  1354. this.y *= num;
  1355. this.z *= num;
  1356. return this;
  1357. };
  1358. /**
  1359. * Returns a new Vector3 copied from the current Vector3.
  1360. */
  1361. Vector3.prototype.clone = function () {
  1362. return new Vector3(this.x, this.y, this.z);
  1363. };
  1364. /**
  1365. * Copies the passed vector coordinates to the current Vector3 ones.
  1366. * Returns the updated Vector3.
  1367. */
  1368. Vector3.prototype.copyFrom = function (source) {
  1369. this.x = source.x;
  1370. this.y = source.y;
  1371. this.z = source.z;
  1372. return this;
  1373. };
  1374. /**
  1375. * Copies the passed floats to the current Vector3 coordinates.
  1376. * Returns the updated Vector3.
  1377. */
  1378. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1379. this.x = x;
  1380. this.y = y;
  1381. this.z = z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Copies the passed floats to the current Vector3 coordinates.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.set = function (x, y, z) {
  1389. return this.copyFromFloats(x, y, z);
  1390. };
  1391. // Statics
  1392. /**
  1393. *
  1394. */
  1395. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1396. var d0 = Vector3.Dot(vector0, axis) - size;
  1397. var d1 = Vector3.Dot(vector1, axis) - size;
  1398. var s = d0 / (d0 - d1);
  1399. return s;
  1400. };
  1401. /**
  1402. * Returns a new Vector3 set from the index "offset" of the passed array.
  1403. */
  1404. Vector3.FromArray = function (array, offset) {
  1405. if (!offset) {
  1406. offset = 0;
  1407. }
  1408. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1409. };
  1410. /**
  1411. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1412. * This function is deprecated. Use FromArray instead.
  1413. */
  1414. Vector3.FromFloatArray = function (array, offset) {
  1415. return Vector3.FromArray(array, offset);
  1416. };
  1417. /**
  1418. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1419. */
  1420. Vector3.FromArrayToRef = function (array, offset, result) {
  1421. result.x = array[offset];
  1422. result.y = array[offset + 1];
  1423. result.z = array[offset + 2];
  1424. };
  1425. /**
  1426. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1427. * This function is deprecated. Use FromArrayToRef instead.
  1428. */
  1429. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1430. return Vector3.FromArrayToRef(array, offset, result);
  1431. };
  1432. /**
  1433. * Sets the passed vector "result" with the passed floats.
  1434. */
  1435. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1436. result.x = x;
  1437. result.y = y;
  1438. result.z = z;
  1439. };
  1440. /**
  1441. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1442. */
  1443. Vector3.Zero = function () {
  1444. return new Vector3(0.0, 0.0, 0.0);
  1445. };
  1446. /**
  1447. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1448. */
  1449. Vector3.One = function () {
  1450. return new Vector3(1.0, 1.0, 1.0);
  1451. };
  1452. /**
  1453. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1454. */
  1455. Vector3.Up = function () {
  1456. return new Vector3(0.0, 1.0, 0.0);
  1457. };
  1458. /**
  1459. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1460. */
  1461. Vector3.Forward = function () {
  1462. return new Vector3(0.0, 0.0, 1.0);
  1463. };
  1464. /**
  1465. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1466. */
  1467. Vector3.Right = function () {
  1468. return new Vector3(1.0, 0.0, 0.0);
  1469. };
  1470. /**
  1471. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1472. */
  1473. Vector3.Left = function () {
  1474. return new Vector3(-1.0, 0.0, 0.0);
  1475. };
  1476. /**
  1477. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1478. * This method computes tranformed coordinates only, not transformed direction vectors.
  1479. */
  1480. Vector3.TransformCoordinates = function (vector, transformation) {
  1481. var result = Vector3.Zero();
  1482. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1483. return result;
  1484. };
  1485. /**
  1486. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1487. * This method computes tranformed coordinates only, not transformed direction vectors.
  1488. */
  1489. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1490. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1491. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1492. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1493. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1494. result.x = x / w;
  1495. result.y = y / w;
  1496. result.z = z / w;
  1497. };
  1498. /**
  1499. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1500. * This method computes tranformed coordinates only, not transformed direction vectors.
  1501. */
  1502. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1503. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1504. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1505. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1506. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1507. result.x = rx / rw;
  1508. result.y = ry / rw;
  1509. result.z = rz / rw;
  1510. };
  1511. /**
  1512. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1513. * This methods computes transformed normalized direction vectors only.
  1514. */
  1515. Vector3.TransformNormal = function (vector, transformation) {
  1516. var result = Vector3.Zero();
  1517. Vector3.TransformNormalToRef(vector, transformation, result);
  1518. return result;
  1519. };
  1520. /**
  1521. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1522. * This methods computes transformed normalized direction vectors only.
  1523. */
  1524. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1525. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1526. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1527. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1528. result.x = x;
  1529. result.y = y;
  1530. result.z = z;
  1531. };
  1532. /**
  1533. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1534. * This methods computes transformed normalized direction vectors only.
  1535. */
  1536. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1537. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1538. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1539. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1540. };
  1541. /**
  1542. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1543. */
  1544. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1545. var squared = amount * amount;
  1546. var cubed = amount * squared;
  1547. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1548. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1549. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1550. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1551. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1552. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1553. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1554. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1555. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1556. return new Vector3(x, y, z);
  1557. };
  1558. /**
  1559. * 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".
  1560. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1561. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1562. */
  1563. Vector3.Clamp = function (value, min, max) {
  1564. var x = value.x;
  1565. x = (x > max.x) ? max.x : x;
  1566. x = (x < min.x) ? min.x : x;
  1567. var y = value.y;
  1568. y = (y > max.y) ? max.y : y;
  1569. y = (y < min.y) ? min.y : y;
  1570. var z = value.z;
  1571. z = (z > max.z) ? max.z : z;
  1572. z = (z < min.z) ? min.z : z;
  1573. return new Vector3(x, y, z);
  1574. };
  1575. /**
  1576. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1577. */
  1578. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1579. var squared = amount * amount;
  1580. var cubed = amount * squared;
  1581. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1582. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1583. var part3 = (cubed - (2.0 * squared)) + amount;
  1584. var part4 = cubed - squared;
  1585. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1586. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1587. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1588. return new Vector3(x, y, z);
  1589. };
  1590. /**
  1591. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1592. */
  1593. Vector3.Lerp = function (start, end, amount) {
  1594. var result = new Vector3(0, 0, 0);
  1595. Vector3.LerpToRef(start, end, amount, result);
  1596. return result;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1600. */
  1601. Vector3.LerpToRef = function (start, end, amount, result) {
  1602. result.x = start.x + ((end.x - start.x) * amount);
  1603. result.y = start.y + ((end.y - start.y) * amount);
  1604. result.z = start.z + ((end.z - start.z) * amount);
  1605. };
  1606. /**
  1607. * Returns the dot product (float) between the vectors "left" and "right".
  1608. */
  1609. Vector3.Dot = function (left, right) {
  1610. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1611. };
  1612. /**
  1613. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1614. * The cross product is then orthogonal to both "left" and "right".
  1615. */
  1616. Vector3.Cross = function (left, right) {
  1617. var result = Vector3.Zero();
  1618. Vector3.CrossToRef(left, right, result);
  1619. return result;
  1620. };
  1621. /**
  1622. * Sets the passed vector "result" with the cross product of "left" and "right".
  1623. * The cross product is then orthogonal to both "left" and "right".
  1624. */
  1625. Vector3.CrossToRef = function (left, right, result) {
  1626. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1627. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1628. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1629. result.copyFrom(MathTmp.Vector3[0]);
  1630. };
  1631. /**
  1632. * Returns a new Vector3 as the normalization of the passed vector.
  1633. */
  1634. Vector3.Normalize = function (vector) {
  1635. var result = Vector3.Zero();
  1636. Vector3.NormalizeToRef(vector, result);
  1637. return result;
  1638. };
  1639. /**
  1640. * Sets the passed vector "result" with the normalization of the passed first vector.
  1641. */
  1642. Vector3.NormalizeToRef = function (vector, result) {
  1643. result.copyFrom(vector);
  1644. result.normalize();
  1645. };
  1646. Vector3.Project = function (vector, world, transform, viewport) {
  1647. var cw = viewport.width;
  1648. var ch = viewport.height;
  1649. var cx = viewport.x;
  1650. var cy = viewport.y;
  1651. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1652. 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);
  1653. var matrix = MathTmp.Matrix[0];
  1654. world.multiplyToRef(transform, matrix);
  1655. matrix.multiplyToRef(viewportMatrix, matrix);
  1656. return Vector3.TransformCoordinates(vector, matrix);
  1657. };
  1658. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1659. var matrix = MathTmp.Matrix[0];
  1660. world.multiplyToRef(transform, matrix);
  1661. matrix.invert();
  1662. source.x = source.x / viewportWidth * 2 - 1;
  1663. source.y = -(source.y / viewportHeight * 2 - 1);
  1664. var vector = Vector3.TransformCoordinates(source, matrix);
  1665. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1666. if (MathTools.WithinEpsilon(num, 1.0)) {
  1667. vector = vector.scale(1.0 / num);
  1668. }
  1669. return vector;
  1670. };
  1671. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1672. var matrix = MathTmp.Matrix[0];
  1673. world.multiplyToRef(view, matrix);
  1674. matrix.multiplyToRef(projection, matrix);
  1675. matrix.invert();
  1676. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1677. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1678. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1679. if (MathTools.WithinEpsilon(num, 1.0)) {
  1680. vector = vector.scale(1.0 / num);
  1681. }
  1682. return vector;
  1683. };
  1684. Vector3.Minimize = function (left, right) {
  1685. var min = left.clone();
  1686. min.MinimizeInPlace(right);
  1687. return min;
  1688. };
  1689. Vector3.Maximize = function (left, right) {
  1690. var max = left.clone();
  1691. max.MaximizeInPlace(right);
  1692. return max;
  1693. };
  1694. /**
  1695. * Returns the distance (float) between the vectors "value1" and "value2".
  1696. */
  1697. Vector3.Distance = function (value1, value2) {
  1698. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1699. };
  1700. /**
  1701. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1702. */
  1703. Vector3.DistanceSquared = function (value1, value2) {
  1704. var x = value1.x - value2.x;
  1705. var y = value1.y - value2.y;
  1706. var z = value1.z - value2.z;
  1707. return (x * x) + (y * y) + (z * z);
  1708. };
  1709. /**
  1710. * Returns a new Vector3 located at the center between "value1" and "value2".
  1711. */
  1712. Vector3.Center = function (value1, value2) {
  1713. var center = value1.add(value2);
  1714. center.scaleInPlace(0.5);
  1715. return center;
  1716. };
  1717. /**
  1718. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1719. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1720. * to something in order to rotate it from its local system to the given target system.
  1721. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1722. * Returns a new Vector3.
  1723. */
  1724. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1725. var rotation = Vector3.Zero();
  1726. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1727. return rotation;
  1728. };
  1729. /**
  1730. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1731. */
  1732. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1733. var quat = MathTmp.Quaternion[0];
  1734. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1735. quat.toEulerAnglesToRef(ref);
  1736. };
  1737. return Vector3;
  1738. }());
  1739. BABYLON.Vector3 = Vector3;
  1740. //Vector4 class created for EulerAngle class conversion to Quaternion
  1741. var Vector4 = (function () {
  1742. /**
  1743. * Creates a Vector4 object from the passed floats.
  1744. */
  1745. function Vector4(x, y, z, w) {
  1746. this.x = x;
  1747. this.y = y;
  1748. this.z = z;
  1749. this.w = w;
  1750. }
  1751. /**
  1752. * Returns the string with the Vector4 coordinates.
  1753. */
  1754. Vector4.prototype.toString = function () {
  1755. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1756. };
  1757. /**
  1758. * Returns the string "Vector4".
  1759. */
  1760. Vector4.prototype.getClassName = function () {
  1761. return "Vector4";
  1762. };
  1763. /**
  1764. * Returns the Vector4 hash code.
  1765. */
  1766. Vector4.prototype.getHashCode = function () {
  1767. var hash = this.x || 0;
  1768. hash = (hash * 397) ^ (this.y || 0);
  1769. hash = (hash * 397) ^ (this.z || 0);
  1770. hash = (hash * 397) ^ (this.w || 0);
  1771. return hash;
  1772. };
  1773. // Operators
  1774. /**
  1775. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1776. */
  1777. Vector4.prototype.asArray = function () {
  1778. var result = [];
  1779. this.toArray(result, 0);
  1780. return result;
  1781. };
  1782. /**
  1783. * Populates the passed array from the passed index with the Vector4 coordinates.
  1784. * Returns the Vector4.
  1785. */
  1786. Vector4.prototype.toArray = function (array, index) {
  1787. if (index === undefined) {
  1788. index = 0;
  1789. }
  1790. array[index] = this.x;
  1791. array[index + 1] = this.y;
  1792. array[index + 2] = this.z;
  1793. array[index + 3] = this.w;
  1794. return this;
  1795. };
  1796. /**
  1797. * Adds the passed vector to the current Vector4.
  1798. * Returns the updated Vector4.
  1799. */
  1800. Vector4.prototype.addInPlace = function (otherVector) {
  1801. this.x += otherVector.x;
  1802. this.y += otherVector.y;
  1803. this.z += otherVector.z;
  1804. this.w += otherVector.w;
  1805. return this;
  1806. };
  1807. /**
  1808. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1809. */
  1810. Vector4.prototype.add = function (otherVector) {
  1811. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1812. };
  1813. /**
  1814. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1815. * Returns the current Vector4.
  1816. */
  1817. Vector4.prototype.addToRef = function (otherVector, result) {
  1818. result.x = this.x + otherVector.x;
  1819. result.y = this.y + otherVector.y;
  1820. result.z = this.z + otherVector.z;
  1821. result.w = this.w + otherVector.w;
  1822. return this;
  1823. };
  1824. /**
  1825. * Subtract in place the passed vector from the current Vector4.
  1826. * Returns the updated Vector4.
  1827. */
  1828. Vector4.prototype.subtractInPlace = function (otherVector) {
  1829. this.x -= otherVector.x;
  1830. this.y -= otherVector.y;
  1831. this.z -= otherVector.z;
  1832. this.w -= otherVector.w;
  1833. return this;
  1834. };
  1835. /**
  1836. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1837. */
  1838. Vector4.prototype.subtract = function (otherVector) {
  1839. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1840. };
  1841. /**
  1842. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1843. * Returns the current Vector4.
  1844. */
  1845. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1846. result.x = this.x - otherVector.x;
  1847. result.y = this.y - otherVector.y;
  1848. result.z = this.z - otherVector.z;
  1849. result.w = this.w - otherVector.w;
  1850. return this;
  1851. };
  1852. /**
  1853. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1854. */
  1855. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1856. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1857. };
  1858. /**
  1859. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1860. * Returns the current Vector4.
  1861. */
  1862. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1863. result.x = this.x - x;
  1864. result.y = this.y - y;
  1865. result.z = this.z - z;
  1866. result.w = this.w - w;
  1867. return this;
  1868. };
  1869. /**
  1870. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1871. */
  1872. Vector4.prototype.negate = function () {
  1873. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1874. };
  1875. /**
  1876. * Multiplies the current Vector4 coordinates by scale (float).
  1877. * Returns the updated Vector4.
  1878. */
  1879. Vector4.prototype.scaleInPlace = function (scale) {
  1880. this.x *= scale;
  1881. this.y *= scale;
  1882. this.z *= scale;
  1883. this.w *= scale;
  1884. return this;
  1885. };
  1886. /**
  1887. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1888. */
  1889. Vector4.prototype.scale = function (scale) {
  1890. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1891. };
  1892. /**
  1893. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1894. * Returns the current Vector4.
  1895. */
  1896. Vector4.prototype.scaleToRef = function (scale, result) {
  1897. result.x = this.x * scale;
  1898. result.y = this.y * scale;
  1899. result.z = this.z * scale;
  1900. result.w = this.w * scale;
  1901. return this;
  1902. };
  1903. /**
  1904. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1905. */
  1906. Vector4.prototype.equals = function (otherVector) {
  1907. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1908. };
  1909. /**
  1910. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1911. */
  1912. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1913. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1914. return otherVector
  1915. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1916. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1917. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1918. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1919. };
  1920. /**
  1921. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1922. */
  1923. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1924. return this.x === x && this.y === y && this.z === z && this.w === w;
  1925. };
  1926. /**
  1927. * Multiplies in place the current Vector4 by the passed one.
  1928. * Returns the updated Vector4.
  1929. */
  1930. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1931. this.x *= otherVector.x;
  1932. this.y *= otherVector.y;
  1933. this.z *= otherVector.z;
  1934. this.w *= otherVector.w;
  1935. return this;
  1936. };
  1937. /**
  1938. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1939. */
  1940. Vector4.prototype.multiply = function (otherVector) {
  1941. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1942. };
  1943. /**
  1944. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1945. * Returns the current Vector4.
  1946. */
  1947. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1948. result.x = this.x * otherVector.x;
  1949. result.y = this.y * otherVector.y;
  1950. result.z = this.z * otherVector.z;
  1951. result.w = this.w * otherVector.w;
  1952. return this;
  1953. };
  1954. /**
  1955. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1956. */
  1957. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1958. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1959. };
  1960. /**
  1961. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1962. */
  1963. Vector4.prototype.divide = function (otherVector) {
  1964. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1965. };
  1966. /**
  1967. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1968. * Returns the current Vector4.
  1969. */
  1970. Vector4.prototype.divideToRef = function (otherVector, result) {
  1971. result.x = this.x / otherVector.x;
  1972. result.y = this.y / otherVector.y;
  1973. result.z = this.z / otherVector.z;
  1974. result.w = this.w / otherVector.w;
  1975. return this;
  1976. };
  1977. /**
  1978. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1979. */
  1980. Vector4.prototype.MinimizeInPlace = function (other) {
  1981. if (other.x < this.x)
  1982. this.x = other.x;
  1983. if (other.y < this.y)
  1984. this.y = other.y;
  1985. if (other.z < this.z)
  1986. this.z = other.z;
  1987. if (other.w < this.w)
  1988. this.w = other.w;
  1989. return this;
  1990. };
  1991. /**
  1992. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1993. */
  1994. Vector4.prototype.MaximizeInPlace = function (other) {
  1995. if (other.x > this.x)
  1996. this.x = other.x;
  1997. if (other.y > this.y)
  1998. this.y = other.y;
  1999. if (other.z > this.z)
  2000. this.z = other.z;
  2001. if (other.w > this.w)
  2002. this.w = other.w;
  2003. return this;
  2004. };
  2005. // Properties
  2006. /**
  2007. * Returns the Vector4 length (float).
  2008. */
  2009. Vector4.prototype.length = function () {
  2010. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2011. };
  2012. /**
  2013. * Returns the Vector4 squared length (float).
  2014. */
  2015. Vector4.prototype.lengthSquared = function () {
  2016. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2017. };
  2018. // Methods
  2019. /**
  2020. * Normalizes in place the Vector4.
  2021. * Returns the updated Vector4.
  2022. */
  2023. Vector4.prototype.normalize = function () {
  2024. var len = this.length();
  2025. if (len === 0)
  2026. return this;
  2027. var num = 1.0 / len;
  2028. this.x *= num;
  2029. this.y *= num;
  2030. this.z *= num;
  2031. this.w *= num;
  2032. return this;
  2033. };
  2034. /**
  2035. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2036. */
  2037. Vector4.prototype.toVector3 = function () {
  2038. return new Vector3(this.x, this.y, this.z);
  2039. };
  2040. /**
  2041. * Returns a new Vector4 copied from the current one.
  2042. */
  2043. Vector4.prototype.clone = function () {
  2044. return new Vector4(this.x, this.y, this.z, this.w);
  2045. };
  2046. /**
  2047. * Updates the current Vector4 with the passed one coordinates.
  2048. * Returns the updated Vector4.
  2049. */
  2050. Vector4.prototype.copyFrom = function (source) {
  2051. this.x = source.x;
  2052. this.y = source.y;
  2053. this.z = source.z;
  2054. this.w = source.w;
  2055. return this;
  2056. };
  2057. /**
  2058. * Updates the current Vector4 coordinates with the passed floats.
  2059. * Returns the updated Vector4.
  2060. */
  2061. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2062. this.x = x;
  2063. this.y = y;
  2064. this.z = z;
  2065. this.w = w;
  2066. return this;
  2067. };
  2068. /**
  2069. * Updates the current Vector4 coordinates with the passed floats.
  2070. * Returns the updated Vector4.
  2071. */
  2072. Vector4.prototype.set = function (x, y, z, w) {
  2073. return this.copyFromFloats(x, y, z, w);
  2074. };
  2075. // Statics
  2076. /**
  2077. * Returns a new Vector4 set from the starting index of the passed array.
  2078. */
  2079. Vector4.FromArray = function (array, offset) {
  2080. if (!offset) {
  2081. offset = 0;
  2082. }
  2083. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2084. };
  2085. /**
  2086. * Updates the passed vector "result" from the starting index of the passed array.
  2087. */
  2088. Vector4.FromArrayToRef = function (array, offset, result) {
  2089. result.x = array[offset];
  2090. result.y = array[offset + 1];
  2091. result.z = array[offset + 2];
  2092. result.w = array[offset + 3];
  2093. };
  2094. /**
  2095. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2096. */
  2097. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2098. Vector4.FromArrayToRef(array, offset, result);
  2099. };
  2100. /**
  2101. * Updates the passed vector "result" coordinates from the passed floats.
  2102. */
  2103. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2104. result.x = x;
  2105. result.y = y;
  2106. result.z = z;
  2107. result.w = w;
  2108. };
  2109. /**
  2110. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2111. */
  2112. Vector4.Zero = function () {
  2113. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2114. };
  2115. /**
  2116. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2117. */
  2118. Vector4.One = function () {
  2119. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2120. };
  2121. /**
  2122. * Returns a new normalized Vector4 from the passed one.
  2123. */
  2124. Vector4.Normalize = function (vector) {
  2125. var result = Vector4.Zero();
  2126. Vector4.NormalizeToRef(vector, result);
  2127. return result;
  2128. };
  2129. /**
  2130. * Updates the passed vector "result" from the normalization of the passed one.
  2131. */
  2132. Vector4.NormalizeToRef = function (vector, result) {
  2133. result.copyFrom(vector);
  2134. result.normalize();
  2135. };
  2136. Vector4.Minimize = function (left, right) {
  2137. var min = left.clone();
  2138. min.MinimizeInPlace(right);
  2139. return min;
  2140. };
  2141. Vector4.Maximize = function (left, right) {
  2142. var max = left.clone();
  2143. max.MaximizeInPlace(right);
  2144. return max;
  2145. };
  2146. /**
  2147. * Returns the distance (float) between the vectors "value1" and "value2".
  2148. */
  2149. Vector4.Distance = function (value1, value2) {
  2150. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2151. };
  2152. /**
  2153. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2154. */
  2155. Vector4.DistanceSquared = function (value1, value2) {
  2156. var x = value1.x - value2.x;
  2157. var y = value1.y - value2.y;
  2158. var z = value1.z - value2.z;
  2159. var w = value1.w - value2.w;
  2160. return (x * x) + (y * y) + (z * z) + (w * w);
  2161. };
  2162. /**
  2163. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2164. */
  2165. Vector4.Center = function (value1, value2) {
  2166. var center = value1.add(value2);
  2167. center.scaleInPlace(0.5);
  2168. return center;
  2169. };
  2170. /**
  2171. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2172. * This methods computes transformed normalized direction vectors only.
  2173. */
  2174. Vector4.TransformNormal = function (vector, transformation) {
  2175. var result = Vector4.Zero();
  2176. Vector4.TransformNormalToRef(vector, transformation, result);
  2177. return result;
  2178. };
  2179. /**
  2180. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2181. * This methods computes transformed normalized direction vectors only.
  2182. */
  2183. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2184. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2185. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2186. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2187. result.x = x;
  2188. result.y = y;
  2189. result.z = z;
  2190. result.w = vector.w;
  2191. };
  2192. /**
  2193. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2194. * This methods computes transformed normalized direction vectors only.
  2195. */
  2196. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2197. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2198. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2199. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2200. result.w = w;
  2201. };
  2202. return Vector4;
  2203. }());
  2204. BABYLON.Vector4 = Vector4;
  2205. var Size = (function () {
  2206. /**
  2207. * Creates a Size object from the passed width and height (floats).
  2208. */
  2209. function Size(width, height) {
  2210. this.width = width;
  2211. this.height = height;
  2212. }
  2213. // Returns a string with the Size width and height.
  2214. Size.prototype.toString = function () {
  2215. return "{W: " + this.width + ", H: " + this.height + "}";
  2216. };
  2217. /**
  2218. * Returns the string "Size"
  2219. */
  2220. Size.prototype.getClassName = function () {
  2221. return "Size";
  2222. };
  2223. /**
  2224. * Returns the Size hash code.
  2225. */
  2226. Size.prototype.getHashCode = function () {
  2227. var hash = this.width || 0;
  2228. hash = (hash * 397) ^ (this.height || 0);
  2229. return hash;
  2230. };
  2231. /**
  2232. * Updates the current size from the passed one.
  2233. * Returns the updated Size.
  2234. */
  2235. Size.prototype.copyFrom = function (src) {
  2236. this.width = src.width;
  2237. this.height = src.height;
  2238. };
  2239. /**
  2240. * Updates in place the current Size from the passed floats.
  2241. * Returns the updated Size.
  2242. */
  2243. Size.prototype.copyFromFloats = function (width, height) {
  2244. this.width = width;
  2245. this.height = height;
  2246. return this;
  2247. };
  2248. /**
  2249. * Updates in place the current Size from the passed floats.
  2250. * Returns the updated Size.
  2251. */
  2252. Size.prototype.set = function (width, height) {
  2253. return this.copyFromFloats(width, height);
  2254. };
  2255. /**
  2256. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2257. */
  2258. Size.prototype.multiplyByFloats = function (w, h) {
  2259. return new Size(this.width * w, this.height * h);
  2260. };
  2261. /**
  2262. * Returns a new Size copied from the passed one.
  2263. */
  2264. Size.prototype.clone = function () {
  2265. return new Size(this.width, this.height);
  2266. };
  2267. /**
  2268. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2269. */
  2270. Size.prototype.equals = function (other) {
  2271. if (!other) {
  2272. return false;
  2273. }
  2274. return (this.width === other.width) && (this.height === other.height);
  2275. };
  2276. Object.defineProperty(Size.prototype, "surface", {
  2277. /**
  2278. * Returns the surface of the Size : width * height (float).
  2279. */
  2280. get: function () {
  2281. return this.width * this.height;
  2282. },
  2283. enumerable: true,
  2284. configurable: true
  2285. });
  2286. /**
  2287. * Returns a new Size set to (0.0, 0.0)
  2288. */
  2289. Size.Zero = function () {
  2290. return new Size(0.0, 0.0);
  2291. };
  2292. /**
  2293. * Returns a new Size set as the addition result of the current Size and the passed one.
  2294. */
  2295. Size.prototype.add = function (otherSize) {
  2296. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2297. return r;
  2298. };
  2299. /**
  2300. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2301. */
  2302. Size.prototype.subtract = function (otherSize) {
  2303. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2304. return r;
  2305. };
  2306. /**
  2307. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2308. */
  2309. Size.Lerp = function (start, end, amount) {
  2310. var w = start.width + ((end.width - start.width) * amount);
  2311. var h = start.height + ((end.height - start.height) * amount);
  2312. return new Size(w, h);
  2313. };
  2314. return Size;
  2315. }());
  2316. BABYLON.Size = Size;
  2317. var Quaternion = (function () {
  2318. /**
  2319. * Creates a new Quaternion from the passed floats.
  2320. */
  2321. function Quaternion(x, y, z, w) {
  2322. if (x === void 0) { x = 0.0; }
  2323. if (y === void 0) { y = 0.0; }
  2324. if (z === void 0) { z = 0.0; }
  2325. if (w === void 0) { w = 1.0; }
  2326. this.x = x;
  2327. this.y = y;
  2328. this.z = z;
  2329. this.w = w;
  2330. }
  2331. /**
  2332. * Returns a string with the Quaternion coordinates.
  2333. */
  2334. Quaternion.prototype.toString = function () {
  2335. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2336. };
  2337. /**
  2338. * Returns the string "Quaternion".
  2339. */
  2340. Quaternion.prototype.getClassName = function () {
  2341. return "Quaternion";
  2342. };
  2343. /**
  2344. * Returns the Quaternion hash code.
  2345. */
  2346. Quaternion.prototype.getHashCode = function () {
  2347. var hash = this.x || 0;
  2348. hash = (hash * 397) ^ (this.y || 0);
  2349. hash = (hash * 397) ^ (this.z || 0);
  2350. hash = (hash * 397) ^ (this.w || 0);
  2351. return hash;
  2352. };
  2353. /**
  2354. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2355. */
  2356. Quaternion.prototype.asArray = function () {
  2357. return [this.x, this.y, this.z, this.w];
  2358. };
  2359. /**
  2360. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2361. */
  2362. Quaternion.prototype.equals = function (otherQuaternion) {
  2363. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2364. };
  2365. /**
  2366. * Returns a new Quaternion copied from the current one.
  2367. */
  2368. Quaternion.prototype.clone = function () {
  2369. return new Quaternion(this.x, this.y, this.z, this.w);
  2370. };
  2371. /**
  2372. * Updates the current Quaternion from the passed one coordinates.
  2373. * Returns the updated Quaterion.
  2374. */
  2375. Quaternion.prototype.copyFrom = function (other) {
  2376. this.x = other.x;
  2377. this.y = other.y;
  2378. this.z = other.z;
  2379. this.w = other.w;
  2380. return this;
  2381. };
  2382. /**
  2383. * Updates the current Quaternion from the passed float coordinates.
  2384. * Returns the updated Quaterion.
  2385. */
  2386. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2387. this.x = x;
  2388. this.y = y;
  2389. this.z = z;
  2390. this.w = w;
  2391. return this;
  2392. };
  2393. /**
  2394. * Updates the current Quaternion from the passed float coordinates.
  2395. * Returns the updated Quaterion.
  2396. */
  2397. Quaternion.prototype.set = function (x, y, z, w) {
  2398. return this.copyFromFloats(x, y, z, w);
  2399. };
  2400. /**
  2401. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2402. */
  2403. Quaternion.prototype.add = function (other) {
  2404. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2405. };
  2406. /**
  2407. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2408. */
  2409. Quaternion.prototype.subtract = function (other) {
  2410. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2411. };
  2412. /**
  2413. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2414. */
  2415. Quaternion.prototype.scale = function (value) {
  2416. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2417. };
  2418. /**
  2419. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2420. */
  2421. Quaternion.prototype.multiply = function (q1) {
  2422. var result = new Quaternion(0, 0, 0, 1.0);
  2423. this.multiplyToRef(q1, result);
  2424. return result;
  2425. };
  2426. /**
  2427. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2428. * Returns the current Quaternion.
  2429. */
  2430. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2431. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2432. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2433. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2434. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2435. result.copyFromFloats(x, y, z, w);
  2436. return this;
  2437. };
  2438. /**
  2439. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2440. * Returns the updated Quaternion.
  2441. */
  2442. Quaternion.prototype.multiplyInPlace = function (q1) {
  2443. this.multiplyToRef(q1, this);
  2444. return this;
  2445. };
  2446. /**
  2447. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2448. * Returns the current Quaternion.
  2449. */
  2450. Quaternion.prototype.conjugateToRef = function (ref) {
  2451. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2452. return this;
  2453. };
  2454. /**
  2455. * Conjugates in place the current Quaternion.
  2456. * Returns the updated Quaternion.
  2457. */
  2458. Quaternion.prototype.conjugateInPlace = function () {
  2459. this.x *= -1;
  2460. this.y *= -1;
  2461. this.z *= -1;
  2462. return this;
  2463. };
  2464. /**
  2465. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2466. */
  2467. Quaternion.prototype.conjugate = function () {
  2468. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2469. return result;
  2470. };
  2471. /**
  2472. * Returns the Quaternion length (float).
  2473. */
  2474. Quaternion.prototype.length = function () {
  2475. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2476. };
  2477. /**
  2478. * Normalize in place the current Quaternion.
  2479. * Returns the updated Quaternion.
  2480. */
  2481. Quaternion.prototype.normalize = function () {
  2482. var length = 1.0 / this.length();
  2483. this.x *= length;
  2484. this.y *= length;
  2485. this.z *= length;
  2486. this.w *= length;
  2487. return this;
  2488. };
  2489. /**
  2490. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2491. */
  2492. Quaternion.prototype.toEulerAngles = function (order) {
  2493. if (order === void 0) { order = "YZX"; }
  2494. var result = Vector3.Zero();
  2495. this.toEulerAnglesToRef(result, order);
  2496. return result;
  2497. };
  2498. /**
  2499. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2500. * Returns the current Quaternion.
  2501. */
  2502. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2503. if (order === void 0) { order = "YZX"; }
  2504. var qz = this.z;
  2505. var qx = this.x;
  2506. var qy = this.y;
  2507. var qw = this.w;
  2508. var sqw = qw * qw;
  2509. var sqz = qz * qz;
  2510. var sqx = qx * qx;
  2511. var sqy = qy * qy;
  2512. var zAxisY = qy * qz - qx * qw;
  2513. var limit = .4999999;
  2514. if (zAxisY < -limit) {
  2515. result.y = 2 * Math.atan2(qy, qw);
  2516. result.x = Math.PI / 2;
  2517. result.z = 0;
  2518. }
  2519. else if (zAxisY > limit) {
  2520. result.y = 2 * Math.atan2(qy, qw);
  2521. result.x = -Math.PI / 2;
  2522. result.z = 0;
  2523. }
  2524. else {
  2525. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2526. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2527. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2528. }
  2529. return this;
  2530. };
  2531. /**
  2532. * Updates the passed rotation matrix with the current Quaternion values.
  2533. * Returns the current Quaternion.
  2534. */
  2535. Quaternion.prototype.toRotationMatrix = function (result) {
  2536. var xx = this.x * this.x;
  2537. var yy = this.y * this.y;
  2538. var zz = this.z * this.z;
  2539. var xy = this.x * this.y;
  2540. var zw = this.z * this.w;
  2541. var zx = this.z * this.x;
  2542. var yw = this.y * this.w;
  2543. var yz = this.y * this.z;
  2544. var xw = this.x * this.w;
  2545. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2546. result.m[1] = 2.0 * (xy + zw);
  2547. result.m[2] = 2.0 * (zx - yw);
  2548. result.m[3] = 0;
  2549. result.m[4] = 2.0 * (xy - zw);
  2550. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2551. result.m[6] = 2.0 * (yz + xw);
  2552. result.m[7] = 0;
  2553. result.m[8] = 2.0 * (zx + yw);
  2554. result.m[9] = 2.0 * (yz - xw);
  2555. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2556. result.m[11] = 0;
  2557. result.m[12] = 0;
  2558. result.m[13] = 0;
  2559. result.m[14] = 0;
  2560. result.m[15] = 1.0;
  2561. result._markAsUpdated();
  2562. return this;
  2563. };
  2564. /**
  2565. * Updates the current Quaternion from the passed rotation matrix values.
  2566. * Returns the updated Quaternion.
  2567. */
  2568. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2569. Quaternion.FromRotationMatrixToRef(matrix, this);
  2570. return this;
  2571. };
  2572. // Statics
  2573. /**
  2574. * Returns a new Quaternion set from the passed rotation matrix values.
  2575. */
  2576. Quaternion.FromRotationMatrix = function (matrix) {
  2577. var result = new Quaternion();
  2578. Quaternion.FromRotationMatrixToRef(matrix, result);
  2579. return result;
  2580. };
  2581. /**
  2582. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2583. */
  2584. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2585. var data = matrix.m;
  2586. var m11 = data[0], m12 = data[4], m13 = data[8];
  2587. var m21 = data[1], m22 = data[5], m23 = data[9];
  2588. var m31 = data[2], m32 = data[6], m33 = data[10];
  2589. var trace = m11 + m22 + m33;
  2590. var s;
  2591. if (trace > 0) {
  2592. s = 0.5 / Math.sqrt(trace + 1.0);
  2593. result.w = 0.25 / s;
  2594. result.x = (m32 - m23) * s;
  2595. result.y = (m13 - m31) * s;
  2596. result.z = (m21 - m12) * s;
  2597. }
  2598. else if (m11 > m22 && m11 > m33) {
  2599. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2600. result.w = (m32 - m23) / s;
  2601. result.x = 0.25 * s;
  2602. result.y = (m12 + m21) / s;
  2603. result.z = (m13 + m31) / s;
  2604. }
  2605. else if (m22 > m33) {
  2606. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2607. result.w = (m13 - m31) / s;
  2608. result.x = (m12 + m21) / s;
  2609. result.y = 0.25 * s;
  2610. result.z = (m23 + m32) / s;
  2611. }
  2612. else {
  2613. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2614. result.w = (m21 - m12) / s;
  2615. result.x = (m13 + m31) / s;
  2616. result.y = (m23 + m32) / s;
  2617. result.z = 0.25 * s;
  2618. }
  2619. };
  2620. /**
  2621. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2622. */
  2623. Quaternion.Zero = function () {
  2624. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2625. };
  2626. /**
  2627. * Returns a new Quaternion as the inverted current Quaternion.
  2628. */
  2629. Quaternion.Inverse = function (q) {
  2630. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2631. };
  2632. /**
  2633. * Returns the identity Quaternion.
  2634. */
  2635. Quaternion.Identity = function () {
  2636. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2637. };
  2638. Quaternion.IsIdentity = function (quaternion) {
  2639. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2640. };
  2641. /**
  2642. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2643. */
  2644. Quaternion.RotationAxis = function (axis, angle) {
  2645. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2646. };
  2647. /**
  2648. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2649. */
  2650. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2651. var sin = Math.sin(angle / 2);
  2652. axis.normalize();
  2653. result.w = Math.cos(angle / 2);
  2654. result.x = axis.x * sin;
  2655. result.y = axis.y * sin;
  2656. result.z = axis.z * sin;
  2657. return result;
  2658. };
  2659. /**
  2660. * Retuns a new Quaternion set from the starting index of the passed array.
  2661. */
  2662. Quaternion.FromArray = function (array, offset) {
  2663. if (!offset) {
  2664. offset = 0;
  2665. }
  2666. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2667. };
  2668. /**
  2669. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2670. */
  2671. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2672. var q = new Quaternion();
  2673. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2674. return q;
  2675. };
  2676. /**
  2677. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2678. */
  2679. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2680. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2681. var halfRoll = roll * 0.5;
  2682. var halfPitch = pitch * 0.5;
  2683. var halfYaw = yaw * 0.5;
  2684. var sinRoll = Math.sin(halfRoll);
  2685. var cosRoll = Math.cos(halfRoll);
  2686. var sinPitch = Math.sin(halfPitch);
  2687. var cosPitch = Math.cos(halfPitch);
  2688. var sinYaw = Math.sin(halfYaw);
  2689. var cosYaw = Math.cos(halfYaw);
  2690. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2691. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2692. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2693. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2694. };
  2695. /**
  2696. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2697. */
  2698. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2699. var result = new Quaternion();
  2700. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2701. return result;
  2702. };
  2703. /**
  2704. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2705. */
  2706. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2707. // Produces a quaternion from Euler angles in the z-x-z orientation
  2708. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2709. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2710. var halfBeta = beta * 0.5;
  2711. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2712. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2713. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2714. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2715. };
  2716. /**
  2717. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2718. * cf to Vector3.RotationFromAxis() documentation.
  2719. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2720. */
  2721. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2722. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2723. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2724. return quat;
  2725. };
  2726. /**
  2727. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2728. * cf to Vector3.RotationFromAxis() documentation.
  2729. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2730. */
  2731. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2732. var rotMat = MathTmp.Matrix[0];
  2733. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2734. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2735. };
  2736. Quaternion.Slerp = function (left, right, amount) {
  2737. var result = Quaternion.Identity();
  2738. Quaternion.SlerpToRef(left, right, amount, result);
  2739. return result;
  2740. };
  2741. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2742. var num2;
  2743. var num3;
  2744. var num = amount;
  2745. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2746. var flag = false;
  2747. if (num4 < 0) {
  2748. flag = true;
  2749. num4 = -num4;
  2750. }
  2751. if (num4 > 0.999999) {
  2752. num3 = 1 - num;
  2753. num2 = flag ? -num : num;
  2754. }
  2755. else {
  2756. var num5 = Math.acos(num4);
  2757. var num6 = (1.0 / Math.sin(num5));
  2758. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2759. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2760. }
  2761. result.x = (num3 * left.x) + (num2 * right.x);
  2762. result.y = (num3 * left.y) + (num2 * right.y);
  2763. result.z = (num3 * left.z) + (num2 * right.z);
  2764. result.w = (num3 * left.w) + (num2 * right.w);
  2765. };
  2766. /**
  2767. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2768. */
  2769. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2770. var squared = amount * amount;
  2771. var cubed = amount * squared;
  2772. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2773. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2774. var part3 = (cubed - (2.0 * squared)) + amount;
  2775. var part4 = cubed - squared;
  2776. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2777. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2778. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2779. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2780. return new Quaternion(x, y, z, w);
  2781. };
  2782. return Quaternion;
  2783. }());
  2784. BABYLON.Quaternion = Quaternion;
  2785. var Matrix = (function () {
  2786. function Matrix() {
  2787. this._isIdentity = false;
  2788. this._isIdentityDirty = true;
  2789. this.m = new Float32Array(16);
  2790. this._markAsUpdated();
  2791. }
  2792. Matrix.prototype._markAsUpdated = function () {
  2793. this.updateFlag = Matrix._updateFlagSeed++;
  2794. this._isIdentityDirty = true;
  2795. };
  2796. // Properties
  2797. /**
  2798. * Boolean : True is the matrix is the identity matrix
  2799. */
  2800. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2801. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2802. if (this._isIdentityDirty) {
  2803. this._isIdentityDirty = false;
  2804. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2805. this._isIdentity = false;
  2806. }
  2807. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2808. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2809. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2810. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2811. this._isIdentity = false;
  2812. }
  2813. else {
  2814. this._isIdentity = true;
  2815. }
  2816. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2817. this._isIdentity = false;
  2818. }
  2819. }
  2820. return this._isIdentity;
  2821. };
  2822. /**
  2823. * Returns the matrix determinant (float).
  2824. */
  2825. Matrix.prototype.determinant = function () {
  2826. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2827. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2828. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2829. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2830. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2831. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2832. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2833. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2834. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2835. };
  2836. // Methods
  2837. /**
  2838. * Returns the matrix underlying array.
  2839. */
  2840. Matrix.prototype.toArray = function () {
  2841. return this.m;
  2842. };
  2843. /**
  2844. * Returns the matrix underlying array.
  2845. */
  2846. Matrix.prototype.asArray = function () {
  2847. return this.toArray();
  2848. };
  2849. /**
  2850. * Inverts in place the Matrix.
  2851. * Returns the Matrix inverted.
  2852. */
  2853. Matrix.prototype.invert = function () {
  2854. this.invertToRef(this);
  2855. return this;
  2856. };
  2857. /**
  2858. * Sets all the matrix elements to zero.
  2859. * Returns the Matrix.
  2860. */
  2861. Matrix.prototype.reset = function () {
  2862. for (var index = 0; index < 16; index++) {
  2863. this.m[index] = 0.0;
  2864. }
  2865. this._markAsUpdated();
  2866. return this;
  2867. };
  2868. /**
  2869. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2870. */
  2871. Matrix.prototype.add = function (other) {
  2872. var result = new Matrix();
  2873. this.addToRef(other, result);
  2874. return result;
  2875. };
  2876. /**
  2877. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2878. * Returns the Matrix.
  2879. */
  2880. Matrix.prototype.addToRef = function (other, result) {
  2881. for (var index = 0; index < 16; index++) {
  2882. result.m[index] = this.m[index] + other.m[index];
  2883. }
  2884. result._markAsUpdated();
  2885. return this;
  2886. };
  2887. /**
  2888. * Adds in place the passed matrix to the current Matrix.
  2889. * Returns the updated Matrix.
  2890. */
  2891. Matrix.prototype.addToSelf = function (other) {
  2892. for (var index = 0; index < 16; index++) {
  2893. this.m[index] += other.m[index];
  2894. }
  2895. this._markAsUpdated();
  2896. return this;
  2897. };
  2898. /**
  2899. * Sets the passed matrix with the current inverted Matrix.
  2900. * Returns the unmodified current Matrix.
  2901. */
  2902. Matrix.prototype.invertToRef = function (other) {
  2903. var l1 = this.m[0];
  2904. var l2 = this.m[1];
  2905. var l3 = this.m[2];
  2906. var l4 = this.m[3];
  2907. var l5 = this.m[4];
  2908. var l6 = this.m[5];
  2909. var l7 = this.m[6];
  2910. var l8 = this.m[7];
  2911. var l9 = this.m[8];
  2912. var l10 = this.m[9];
  2913. var l11 = this.m[10];
  2914. var l12 = this.m[11];
  2915. var l13 = this.m[12];
  2916. var l14 = this.m[13];
  2917. var l15 = this.m[14];
  2918. var l16 = this.m[15];
  2919. var l17 = (l11 * l16) - (l12 * l15);
  2920. var l18 = (l10 * l16) - (l12 * l14);
  2921. var l19 = (l10 * l15) - (l11 * l14);
  2922. var l20 = (l9 * l16) - (l12 * l13);
  2923. var l21 = (l9 * l15) - (l11 * l13);
  2924. var l22 = (l9 * l14) - (l10 * l13);
  2925. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2926. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2927. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2928. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2929. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2930. var l28 = (l7 * l16) - (l8 * l15);
  2931. var l29 = (l6 * l16) - (l8 * l14);
  2932. var l30 = (l6 * l15) - (l7 * l14);
  2933. var l31 = (l5 * l16) - (l8 * l13);
  2934. var l32 = (l5 * l15) - (l7 * l13);
  2935. var l33 = (l5 * l14) - (l6 * l13);
  2936. var l34 = (l7 * l12) - (l8 * l11);
  2937. var l35 = (l6 * l12) - (l8 * l10);
  2938. var l36 = (l6 * l11) - (l7 * l10);
  2939. var l37 = (l5 * l12) - (l8 * l9);
  2940. var l38 = (l5 * l11) - (l7 * l9);
  2941. var l39 = (l5 * l10) - (l6 * l9);
  2942. other.m[0] = l23 * l27;
  2943. other.m[4] = l24 * l27;
  2944. other.m[8] = l25 * l27;
  2945. other.m[12] = l26 * l27;
  2946. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2947. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2948. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2949. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2950. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2951. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2952. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2953. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2954. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2955. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2956. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2957. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2958. other._markAsUpdated();
  2959. return this;
  2960. };
  2961. /**
  2962. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2963. * Returns the updated Matrix.
  2964. */
  2965. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2966. this.m[12] = x;
  2967. this.m[13] = y;
  2968. this.m[14] = z;
  2969. this._markAsUpdated();
  2970. return this;
  2971. };
  2972. /**
  2973. * Inserts the translation vector in the current Matrix.
  2974. * Returns the updated Matrix.
  2975. */
  2976. Matrix.prototype.setTranslation = function (vector3) {
  2977. this.m[12] = vector3.x;
  2978. this.m[13] = vector3.y;
  2979. this.m[14] = vector3.z;
  2980. this._markAsUpdated();
  2981. return this;
  2982. };
  2983. /**
  2984. * Returns a new Vector3 as the extracted translation from the Matrix.
  2985. */
  2986. Matrix.prototype.getTranslation = function () {
  2987. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2988. };
  2989. /**
  2990. * Fill a Vector3 with the extracted translation from the Matrix.
  2991. */
  2992. Matrix.prototype.getTranslationToRef = function (result) {
  2993. result.x = this.m[12];
  2994. result.y = this.m[13];
  2995. result.z = this.m[14];
  2996. return this;
  2997. };
  2998. /**
  2999. * Remove rotation and scaling part from the Matrix.
  3000. * Returns the updated Matrix.
  3001. */
  3002. Matrix.prototype.removeRotationAndScaling = function () {
  3003. this.setRowFromFloats(0, 1, 0, 0, 0);
  3004. this.setRowFromFloats(1, 0, 1, 0, 0);
  3005. this.setRowFromFloats(2, 0, 0, 1, 0);
  3006. return this;
  3007. };
  3008. /**
  3009. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3010. */
  3011. Matrix.prototype.multiply = function (other) {
  3012. var result = new Matrix();
  3013. this.multiplyToRef(other, result);
  3014. return result;
  3015. };
  3016. /**
  3017. * Updates the current Matrix from the passed one values.
  3018. * Returns the updated Matrix.
  3019. */
  3020. Matrix.prototype.copyFrom = function (other) {
  3021. for (var index = 0; index < 16; index++) {
  3022. this.m[index] = other.m[index];
  3023. }
  3024. this._markAsUpdated();
  3025. return this;
  3026. };
  3027. /**
  3028. * Populates the passed array from the starting index with the Matrix values.
  3029. * Returns the Matrix.
  3030. */
  3031. Matrix.prototype.copyToArray = function (array, offset) {
  3032. if (offset === void 0) { offset = 0; }
  3033. for (var index = 0; index < 16; index++) {
  3034. array[offset + index] = this.m[index];
  3035. }
  3036. return this;
  3037. };
  3038. /**
  3039. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3040. */
  3041. Matrix.prototype.multiplyToRef = function (other, result) {
  3042. this.multiplyToArray(other, result.m, 0);
  3043. result._markAsUpdated();
  3044. return this;
  3045. };
  3046. /**
  3047. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3048. */
  3049. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3050. var tm0 = this.m[0];
  3051. var tm1 = this.m[1];
  3052. var tm2 = this.m[2];
  3053. var tm3 = this.m[3];
  3054. var tm4 = this.m[4];
  3055. var tm5 = this.m[5];
  3056. var tm6 = this.m[6];
  3057. var tm7 = this.m[7];
  3058. var tm8 = this.m[8];
  3059. var tm9 = this.m[9];
  3060. var tm10 = this.m[10];
  3061. var tm11 = this.m[11];
  3062. var tm12 = this.m[12];
  3063. var tm13 = this.m[13];
  3064. var tm14 = this.m[14];
  3065. var tm15 = this.m[15];
  3066. var om0 = other.m[0];
  3067. var om1 = other.m[1];
  3068. var om2 = other.m[2];
  3069. var om3 = other.m[3];
  3070. var om4 = other.m[4];
  3071. var om5 = other.m[5];
  3072. var om6 = other.m[6];
  3073. var om7 = other.m[7];
  3074. var om8 = other.m[8];
  3075. var om9 = other.m[9];
  3076. var om10 = other.m[10];
  3077. var om11 = other.m[11];
  3078. var om12 = other.m[12];
  3079. var om13 = other.m[13];
  3080. var om14 = other.m[14];
  3081. var om15 = other.m[15];
  3082. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3083. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3084. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3085. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3086. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3087. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3088. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3089. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3090. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3091. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3092. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3093. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3094. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3095. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3096. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3097. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3098. return this;
  3099. };
  3100. /**
  3101. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3102. */
  3103. Matrix.prototype.equals = function (value) {
  3104. return value &&
  3105. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3106. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3107. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3108. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3109. };
  3110. /**
  3111. * Returns a new Matrix from the current Matrix.
  3112. */
  3113. Matrix.prototype.clone = function () {
  3114. 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]);
  3115. };
  3116. /**
  3117. * Returns the string "Matrix"
  3118. */
  3119. Matrix.prototype.getClassName = function () {
  3120. return "Matrix";
  3121. };
  3122. /**
  3123. * Returns the Matrix hash code.
  3124. */
  3125. Matrix.prototype.getHashCode = function () {
  3126. var hash = this.m[0] || 0;
  3127. for (var i = 1; i < 16; i++) {
  3128. hash = (hash * 397) ^ (this.m[i] || 0);
  3129. }
  3130. return hash;
  3131. };
  3132. /**
  3133. * Decomposes the current Matrix into :
  3134. * - a scale vector3 passed as a reference to update,
  3135. * - a rotation quaternion passed as a reference to update,
  3136. * - a translation vector3 passed as a reference to update.
  3137. * Returns the boolean `true`.
  3138. */
  3139. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3140. translation.x = this.m[12];
  3141. translation.y = this.m[13];
  3142. translation.z = this.m[14];
  3143. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3144. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3145. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3146. if (this.determinant() <= 0) {
  3147. scale.y *= -1;
  3148. }
  3149. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3150. rotation.x = 0;
  3151. rotation.y = 0;
  3152. rotation.z = 0;
  3153. rotation.w = 1;
  3154. return false;
  3155. }
  3156. 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]);
  3157. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3158. return true;
  3159. };
  3160. /**
  3161. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3162. */
  3163. Matrix.prototype.getRotationMatrix = function () {
  3164. var result = Matrix.Identity();
  3165. this.getRotationMatrixToRef(result);
  3166. return result;
  3167. };
  3168. /**
  3169. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3170. * Returns the current Matrix.
  3171. */
  3172. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3173. var m = this.m;
  3174. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3175. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3176. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3177. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3178. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3179. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3180. 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);
  3181. return this;
  3182. };
  3183. // Statics
  3184. /**
  3185. * Returns a new Matrix set from the starting index of the passed array.
  3186. */
  3187. Matrix.FromArray = function (array, offset) {
  3188. var result = new Matrix();
  3189. if (!offset) {
  3190. offset = 0;
  3191. }
  3192. Matrix.FromArrayToRef(array, offset, result);
  3193. return result;
  3194. };
  3195. /**
  3196. * Sets the passed "result" matrix from the starting index of the passed array.
  3197. */
  3198. Matrix.FromArrayToRef = function (array, offset, result) {
  3199. for (var index = 0; index < 16; index++) {
  3200. result.m[index] = array[index + offset];
  3201. }
  3202. result._markAsUpdated();
  3203. };
  3204. /**
  3205. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3206. */
  3207. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3208. for (var index = 0; index < 16; index++) {
  3209. result.m[index] = array[index + offset] * scale;
  3210. }
  3211. result._markAsUpdated();
  3212. };
  3213. /**
  3214. * Sets the passed matrix "result" with the 16 passed floats.
  3215. */
  3216. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3217. result.m[0] = initialM11;
  3218. result.m[1] = initialM12;
  3219. result.m[2] = initialM13;
  3220. result.m[3] = initialM14;
  3221. result.m[4] = initialM21;
  3222. result.m[5] = initialM22;
  3223. result.m[6] = initialM23;
  3224. result.m[7] = initialM24;
  3225. result.m[8] = initialM31;
  3226. result.m[9] = initialM32;
  3227. result.m[10] = initialM33;
  3228. result.m[11] = initialM34;
  3229. result.m[12] = initialM41;
  3230. result.m[13] = initialM42;
  3231. result.m[14] = initialM43;
  3232. result.m[15] = initialM44;
  3233. result._markAsUpdated();
  3234. };
  3235. /**
  3236. * Returns the index-th row of the current matrix as a new Vector4.
  3237. */
  3238. Matrix.prototype.getRow = function (index) {
  3239. if (index < 0 || index > 3) {
  3240. return null;
  3241. }
  3242. var i = index * 4;
  3243. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3244. };
  3245. /**
  3246. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3247. * Returns the updated Matrix.
  3248. */
  3249. Matrix.prototype.setRow = function (index, row) {
  3250. if (index < 0 || index > 3) {
  3251. return this;
  3252. }
  3253. var i = index * 4;
  3254. this.m[i + 0] = row.x;
  3255. this.m[i + 1] = row.y;
  3256. this.m[i + 2] = row.z;
  3257. this.m[i + 3] = row.w;
  3258. this._markAsUpdated();
  3259. return this;
  3260. };
  3261. /**
  3262. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3263. * Returns the updated Matrix.
  3264. */
  3265. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3266. if (index < 0 || index > 3) {
  3267. return this;
  3268. }
  3269. var i = index * 4;
  3270. this.m[i + 0] = x;
  3271. this.m[i + 1] = y;
  3272. this.m[i + 2] = z;
  3273. this.m[i + 3] = w;
  3274. this._markAsUpdated();
  3275. return this;
  3276. };
  3277. /**
  3278. * Returns a new Matrix set from the 16 passed floats.
  3279. */
  3280. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3281. var result = new Matrix();
  3282. result.m[0] = initialM11;
  3283. result.m[1] = initialM12;
  3284. result.m[2] = initialM13;
  3285. result.m[3] = initialM14;
  3286. result.m[4] = initialM21;
  3287. result.m[5] = initialM22;
  3288. result.m[6] = initialM23;
  3289. result.m[7] = initialM24;
  3290. result.m[8] = initialM31;
  3291. result.m[9] = initialM32;
  3292. result.m[10] = initialM33;
  3293. result.m[11] = initialM34;
  3294. result.m[12] = initialM41;
  3295. result.m[13] = initialM42;
  3296. result.m[14] = initialM43;
  3297. result.m[15] = initialM44;
  3298. return result;
  3299. };
  3300. /**
  3301. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3302. */
  3303. Matrix.Compose = function (scale, rotation, translation) {
  3304. var result = Matrix.Identity();
  3305. Matrix.ComposeToRef(scale, rotation, translation, result);
  3306. return result;
  3307. };
  3308. /**
  3309. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3310. */
  3311. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3312. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3313. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3314. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3315. result.setTranslation(translation);
  3316. };
  3317. /**
  3318. * Returns a new indentity Matrix.
  3319. */
  3320. Matrix.Identity = function () {
  3321. 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);
  3322. };
  3323. /**
  3324. * Sets the passed "result" as an identity matrix.
  3325. */
  3326. Matrix.IdentityToRef = function (result) {
  3327. 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);
  3328. };
  3329. /**
  3330. * Returns a new zero Matrix.
  3331. */
  3332. Matrix.Zero = function () {
  3333. 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);
  3334. };
  3335. /**
  3336. * Returns a new rotation matrix for "angle" radians around the X axis.
  3337. */
  3338. Matrix.RotationX = function (angle) {
  3339. var result = new Matrix();
  3340. Matrix.RotationXToRef(angle, result);
  3341. return result;
  3342. };
  3343. /**
  3344. * Returns a new Matrix as the passed inverted one.
  3345. */
  3346. Matrix.Invert = function (source) {
  3347. var result = new Matrix();
  3348. source.invertToRef(result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3353. */
  3354. Matrix.RotationXToRef = function (angle, result) {
  3355. var s = Math.sin(angle);
  3356. var c = Math.cos(angle);
  3357. result.m[0] = 1.0;
  3358. result.m[15] = 1.0;
  3359. result.m[5] = c;
  3360. result.m[10] = c;
  3361. result.m[9] = -s;
  3362. result.m[6] = s;
  3363. result.m[1] = 0.0;
  3364. result.m[2] = 0.0;
  3365. result.m[3] = 0.0;
  3366. result.m[4] = 0.0;
  3367. result.m[7] = 0.0;
  3368. result.m[8] = 0.0;
  3369. result.m[11] = 0.0;
  3370. result.m[12] = 0.0;
  3371. result.m[13] = 0.0;
  3372. result.m[14] = 0.0;
  3373. result._markAsUpdated();
  3374. };
  3375. /**
  3376. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3377. */
  3378. Matrix.RotationY = function (angle) {
  3379. var result = new Matrix();
  3380. Matrix.RotationYToRef(angle, result);
  3381. return result;
  3382. };
  3383. /**
  3384. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3385. */
  3386. Matrix.RotationYToRef = function (angle, result) {
  3387. var s = Math.sin(angle);
  3388. var c = Math.cos(angle);
  3389. result.m[5] = 1.0;
  3390. result.m[15] = 1.0;
  3391. result.m[0] = c;
  3392. result.m[2] = -s;
  3393. result.m[8] = s;
  3394. result.m[10] = c;
  3395. result.m[1] = 0.0;
  3396. result.m[3] = 0.0;
  3397. result.m[4] = 0.0;
  3398. result.m[6] = 0.0;
  3399. result.m[7] = 0.0;
  3400. result.m[9] = 0.0;
  3401. result.m[11] = 0.0;
  3402. result.m[12] = 0.0;
  3403. result.m[13] = 0.0;
  3404. result.m[14] = 0.0;
  3405. result._markAsUpdated();
  3406. };
  3407. /**
  3408. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3409. */
  3410. Matrix.RotationZ = function (angle) {
  3411. var result = new Matrix();
  3412. Matrix.RotationZToRef(angle, result);
  3413. return result;
  3414. };
  3415. /**
  3416. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3417. */
  3418. Matrix.RotationZToRef = function (angle, result) {
  3419. var s = Math.sin(angle);
  3420. var c = Math.cos(angle);
  3421. result.m[10] = 1.0;
  3422. result.m[15] = 1.0;
  3423. result.m[0] = c;
  3424. result.m[1] = s;
  3425. result.m[4] = -s;
  3426. result.m[5] = c;
  3427. result.m[2] = 0.0;
  3428. result.m[3] = 0.0;
  3429. result.m[6] = 0.0;
  3430. result.m[7] = 0.0;
  3431. result.m[8] = 0.0;
  3432. result.m[9] = 0.0;
  3433. result.m[11] = 0.0;
  3434. result.m[12] = 0.0;
  3435. result.m[13] = 0.0;
  3436. result.m[14] = 0.0;
  3437. result._markAsUpdated();
  3438. };
  3439. /**
  3440. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3441. */
  3442. Matrix.RotationAxis = function (axis, angle) {
  3443. var result = Matrix.Zero();
  3444. Matrix.RotationAxisToRef(axis, angle, result);
  3445. return result;
  3446. };
  3447. /**
  3448. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3449. */
  3450. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3451. var s = Math.sin(-angle);
  3452. var c = Math.cos(-angle);
  3453. var c1 = 1 - c;
  3454. axis.normalize();
  3455. result.m[0] = (axis.x * axis.x) * c1 + c;
  3456. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3457. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3458. result.m[3] = 0.0;
  3459. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3460. result.m[5] = (axis.y * axis.y) * c1 + c;
  3461. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3462. result.m[7] = 0.0;
  3463. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3464. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3465. result.m[10] = (axis.z * axis.z) * c1 + c;
  3466. result.m[11] = 0.0;
  3467. result.m[15] = 1.0;
  3468. result._markAsUpdated();
  3469. };
  3470. /**
  3471. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3472. */
  3473. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3474. var result = new Matrix();
  3475. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3476. return result;
  3477. };
  3478. /**
  3479. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3480. */
  3481. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3482. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3483. this._tempQuaternion.toRotationMatrix(result);
  3484. };
  3485. /**
  3486. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3487. */
  3488. Matrix.Scaling = function (x, y, z) {
  3489. var result = Matrix.Zero();
  3490. Matrix.ScalingToRef(x, y, z, result);
  3491. return result;
  3492. };
  3493. /**
  3494. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3495. */
  3496. Matrix.ScalingToRef = function (x, y, z, result) {
  3497. result.m[0] = x;
  3498. result.m[1] = 0.0;
  3499. result.m[2] = 0.0;
  3500. result.m[3] = 0.0;
  3501. result.m[4] = 0.0;
  3502. result.m[5] = y;
  3503. result.m[6] = 0.0;
  3504. result.m[7] = 0.0;
  3505. result.m[8] = 0.0;
  3506. result.m[9] = 0.0;
  3507. result.m[10] = z;
  3508. result.m[11] = 0.0;
  3509. result.m[12] = 0.0;
  3510. result.m[13] = 0.0;
  3511. result.m[14] = 0.0;
  3512. result.m[15] = 1.0;
  3513. result._markAsUpdated();
  3514. };
  3515. /**
  3516. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3517. */
  3518. Matrix.Translation = function (x, y, z) {
  3519. var result = Matrix.Identity();
  3520. Matrix.TranslationToRef(x, y, z, result);
  3521. return result;
  3522. };
  3523. /**
  3524. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3525. */
  3526. Matrix.TranslationToRef = function (x, y, z, result) {
  3527. 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);
  3528. };
  3529. /**
  3530. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3531. */
  3532. Matrix.Lerp = function (startValue, endValue, gradient) {
  3533. var result = Matrix.Zero();
  3534. for (var index = 0; index < 16; index++) {
  3535. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3536. }
  3537. result._markAsUpdated();
  3538. return result;
  3539. };
  3540. /**
  3541. * Returns a new Matrix whose values are computed by :
  3542. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3543. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3544. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3545. */
  3546. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3547. var startScale = new Vector3(0, 0, 0);
  3548. var startRotation = new Quaternion();
  3549. var startTranslation = new Vector3(0, 0, 0);
  3550. startValue.decompose(startScale, startRotation, startTranslation);
  3551. var endScale = new Vector3(0, 0, 0);
  3552. var endRotation = new Quaternion();
  3553. var endTranslation = new Vector3(0, 0, 0);
  3554. endValue.decompose(endScale, endRotation, endTranslation);
  3555. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3556. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3557. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3558. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3559. };
  3560. /**
  3561. * 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".
  3562. * This methods works for a Left-Handed system.
  3563. */
  3564. Matrix.LookAtLH = function (eye, target, up) {
  3565. var result = Matrix.Zero();
  3566. Matrix.LookAtLHToRef(eye, target, up, result);
  3567. return result;
  3568. };
  3569. /**
  3570. * 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".
  3571. * This methods works for a Left-Handed system.
  3572. */
  3573. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3574. // Z axis
  3575. target.subtractToRef(eye, this._zAxis);
  3576. this._zAxis.normalize();
  3577. // X axis
  3578. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3579. if (this._xAxis.lengthSquared() === 0) {
  3580. this._xAxis.x = 1.0;
  3581. }
  3582. else {
  3583. this._xAxis.normalize();
  3584. }
  3585. // Y axis
  3586. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3587. this._yAxis.normalize();
  3588. // Eye angles
  3589. var ex = -Vector3.Dot(this._xAxis, eye);
  3590. var ey = -Vector3.Dot(this._yAxis, eye);
  3591. var ez = -Vector3.Dot(this._zAxis, eye);
  3592. 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);
  3593. };
  3594. /**
  3595. * 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".
  3596. * This methods works for a Right-Handed system.
  3597. */
  3598. Matrix.LookAtRH = function (eye, target, up) {
  3599. var result = Matrix.Zero();
  3600. Matrix.LookAtRHToRef(eye, target, up, result);
  3601. return result;
  3602. };
  3603. /**
  3604. * 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".
  3605. * This methods works for a Left-Handed system.
  3606. */
  3607. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3608. // Z axis
  3609. eye.subtractToRef(target, this._zAxis);
  3610. this._zAxis.normalize();
  3611. // X axis
  3612. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3613. if (this._xAxis.lengthSquared() === 0) {
  3614. this._xAxis.x = 1.0;
  3615. }
  3616. else {
  3617. this._xAxis.normalize();
  3618. }
  3619. // Y axis
  3620. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3621. this._yAxis.normalize();
  3622. // Eye angles
  3623. var ex = -Vector3.Dot(this._xAxis, eye);
  3624. var ey = -Vector3.Dot(this._yAxis, eye);
  3625. var ez = -Vector3.Dot(this._zAxis, eye);
  3626. 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);
  3627. };
  3628. /**
  3629. * 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.
  3630. */
  3631. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3632. var matrix = Matrix.Zero();
  3633. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3634. return matrix;
  3635. };
  3636. /**
  3637. * 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.
  3638. */
  3639. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3640. var n = znear;
  3641. var f = zfar;
  3642. var a = 2.0 / width;
  3643. var b = 2.0 / height;
  3644. var c = 2.0 / (f - n);
  3645. var d = -(f + n) / (f - n);
  3646. 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);
  3647. };
  3648. /**
  3649. * 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.
  3650. */
  3651. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3652. var matrix = Matrix.Zero();
  3653. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3654. return matrix;
  3655. };
  3656. /**
  3657. * 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.
  3658. */
  3659. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3660. var n = znear;
  3661. var f = zfar;
  3662. var a = 2.0 / (right - left);
  3663. var b = 2.0 / (top - bottom);
  3664. var c = 2.0 / (f - n);
  3665. var d = -(f + n) / (f - n);
  3666. var i0 = (left + right) / (left - right);
  3667. var i1 = (top + bottom) / (bottom - top);
  3668. 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);
  3669. };
  3670. /**
  3671. * 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.
  3672. */
  3673. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3674. var matrix = Matrix.Zero();
  3675. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3676. return matrix;
  3677. };
  3678. /**
  3679. * 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.
  3680. */
  3681. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3682. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3683. result.m[10] *= -1.0;
  3684. };
  3685. /**
  3686. * 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.
  3687. */
  3688. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3689. var matrix = Matrix.Zero();
  3690. var n = znear;
  3691. var f = zfar;
  3692. var a = 2.0 * n / width;
  3693. var b = 2.0 * n / height;
  3694. var c = (f + n) / (f - n);
  3695. var d = -2.0 * f * n / (f - n);
  3696. 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);
  3697. return matrix;
  3698. };
  3699. /**
  3700. * 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.
  3701. */
  3702. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3703. var matrix = Matrix.Zero();
  3704. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3705. return matrix;
  3706. };
  3707. /**
  3708. * 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.
  3709. */
  3710. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3711. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3712. var n = znear;
  3713. var f = zfar;
  3714. var t = 1.0 / (Math.tan(fov * 0.5));
  3715. var a = isVerticalFovFixed ? (t / aspect) : t;
  3716. var b = isVerticalFovFixed ? t : (t * aspect);
  3717. var c = (f + n) / (f - n);
  3718. var d = -2.0 * f * n / (f - n);
  3719. 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);
  3720. };
  3721. /**
  3722. * 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.
  3723. */
  3724. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3725. var matrix = Matrix.Zero();
  3726. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3727. return matrix;
  3728. };
  3729. /**
  3730. * 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.
  3731. */
  3732. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3733. //alternatively this could be expressed as:
  3734. // m = PerspectiveFovLHToRef
  3735. // m[10] *= -1.0;
  3736. // m[11] *= -1.0;
  3737. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3738. var n = znear;
  3739. var f = zfar;
  3740. var t = 1.0 / (Math.tan(fov * 0.5));
  3741. var a = isVerticalFovFixed ? (t / aspect) : t;
  3742. var b = isVerticalFovFixed ? t : (t * aspect);
  3743. var c = -(f + n) / (f - n);
  3744. var d = -2 * f * n / (f - n);
  3745. 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);
  3746. };
  3747. /**
  3748. * 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.
  3749. */
  3750. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3751. if (rightHanded === void 0) { rightHanded = false; }
  3752. var rightHandedFactor = rightHanded ? -1 : 1;
  3753. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3754. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3755. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3756. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3757. var xScale = 2.0 / (leftTan + rightTan);
  3758. var yScale = 2.0 / (upTan + downTan);
  3759. result.m[0] = xScale;
  3760. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3761. result.m[5] = yScale;
  3762. result.m[6] = result.m[7] = 0.0;
  3763. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3764. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3765. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3766. result.m[10] = -zfar / (znear - zfar);
  3767. result.m[11] = 1.0 * rightHandedFactor;
  3768. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3769. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3770. // result.m[14] = (znear * zfar) / (znear - zfar);
  3771. result._markAsUpdated();
  3772. };
  3773. /**
  3774. * Returns the final transformation matrix : world * view * projection * viewport
  3775. */
  3776. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3777. var cw = viewport.width;
  3778. var ch = viewport.height;
  3779. var cx = viewport.x;
  3780. var cy = viewport.y;
  3781. 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);
  3782. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3783. };
  3784. /**
  3785. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3786. */
  3787. Matrix.GetAsMatrix2x2 = function (matrix) {
  3788. return new Float32Array([
  3789. matrix.m[0], matrix.m[1],
  3790. matrix.m[4], matrix.m[5]
  3791. ]);
  3792. };
  3793. /**
  3794. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3795. */
  3796. Matrix.GetAsMatrix3x3 = function (matrix) {
  3797. return new Float32Array([
  3798. matrix.m[0], matrix.m[1], matrix.m[2],
  3799. matrix.m[4], matrix.m[5], matrix.m[6],
  3800. matrix.m[8], matrix.m[9], matrix.m[10]
  3801. ]);
  3802. };
  3803. /**
  3804. * Compute the transpose of the passed Matrix.
  3805. * Returns a new Matrix.
  3806. */
  3807. Matrix.Transpose = function (matrix) {
  3808. var result = new Matrix();
  3809. result.m[0] = matrix.m[0];
  3810. result.m[1] = matrix.m[4];
  3811. result.m[2] = matrix.m[8];
  3812. result.m[3] = matrix.m[12];
  3813. result.m[4] = matrix.m[1];
  3814. result.m[5] = matrix.m[5];
  3815. result.m[6] = matrix.m[9];
  3816. result.m[7] = matrix.m[13];
  3817. result.m[8] = matrix.m[2];
  3818. result.m[9] = matrix.m[6];
  3819. result.m[10] = matrix.m[10];
  3820. result.m[11] = matrix.m[14];
  3821. result.m[12] = matrix.m[3];
  3822. result.m[13] = matrix.m[7];
  3823. result.m[14] = matrix.m[11];
  3824. result.m[15] = matrix.m[15];
  3825. return result;
  3826. };
  3827. /**
  3828. * Returns a new Matrix as the reflection matrix across the passed plane.
  3829. */
  3830. Matrix.Reflection = function (plane) {
  3831. var matrix = new Matrix();
  3832. Matrix.ReflectionToRef(plane, matrix);
  3833. return matrix;
  3834. };
  3835. /**
  3836. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3837. */
  3838. Matrix.ReflectionToRef = function (plane, result) {
  3839. plane.normalize();
  3840. var x = plane.normal.x;
  3841. var y = plane.normal.y;
  3842. var z = plane.normal.z;
  3843. var temp = -2 * x;
  3844. var temp2 = -2 * y;
  3845. var temp3 = -2 * z;
  3846. result.m[0] = (temp * x) + 1;
  3847. result.m[1] = temp2 * x;
  3848. result.m[2] = temp3 * x;
  3849. result.m[3] = 0.0;
  3850. result.m[4] = temp * y;
  3851. result.m[5] = (temp2 * y) + 1;
  3852. result.m[6] = temp3 * y;
  3853. result.m[7] = 0.0;
  3854. result.m[8] = temp * z;
  3855. result.m[9] = temp2 * z;
  3856. result.m[10] = (temp3 * z) + 1;
  3857. result.m[11] = 0.0;
  3858. result.m[12] = temp * plane.d;
  3859. result.m[13] = temp2 * plane.d;
  3860. result.m[14] = temp3 * plane.d;
  3861. result.m[15] = 1.0;
  3862. result._markAsUpdated();
  3863. };
  3864. /**
  3865. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3866. */
  3867. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3868. result.m[0] = xaxis.x;
  3869. result.m[1] = xaxis.y;
  3870. result.m[2] = xaxis.z;
  3871. result.m[3] = 0.0;
  3872. result.m[4] = yaxis.x;
  3873. result.m[5] = yaxis.y;
  3874. result.m[6] = yaxis.z;
  3875. result.m[7] = 0.0;
  3876. result.m[8] = zaxis.x;
  3877. result.m[9] = zaxis.y;
  3878. result.m[10] = zaxis.z;
  3879. result.m[11] = 0.0;
  3880. result.m[12] = 0.0;
  3881. result.m[13] = 0.0;
  3882. result.m[14] = 0.0;
  3883. result.m[15] = 1.0;
  3884. result._markAsUpdated();
  3885. };
  3886. /**
  3887. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3888. */
  3889. Matrix.FromQuaternionToRef = function (quat, result) {
  3890. var xx = quat.x * quat.x;
  3891. var yy = quat.y * quat.y;
  3892. var zz = quat.z * quat.z;
  3893. var xy = quat.x * quat.y;
  3894. var zw = quat.z * quat.w;
  3895. var zx = quat.z * quat.x;
  3896. var yw = quat.y * quat.w;
  3897. var yz = quat.y * quat.z;
  3898. var xw = quat.x * quat.w;
  3899. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3900. result.m[1] = 2.0 * (xy + zw);
  3901. result.m[2] = 2.0 * (zx - yw);
  3902. result.m[3] = 0.0;
  3903. result.m[4] = 2.0 * (xy - zw);
  3904. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3905. result.m[6] = 2.0 * (yz + xw);
  3906. result.m[7] = 0.0;
  3907. result.m[8] = 2.0 * (zx + yw);
  3908. result.m[9] = 2.0 * (yz - xw);
  3909. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3910. result.m[11] = 0.0;
  3911. result.m[12] = 0.0;
  3912. result.m[13] = 0.0;
  3913. result.m[14] = 0.0;
  3914. result.m[15] = 1.0;
  3915. result._markAsUpdated();
  3916. };
  3917. return Matrix;
  3918. }());
  3919. Matrix._tempQuaternion = new Quaternion();
  3920. Matrix._xAxis = Vector3.Zero();
  3921. Matrix._yAxis = Vector3.Zero();
  3922. Matrix._zAxis = Vector3.Zero();
  3923. Matrix._updateFlagSeed = 0;
  3924. BABYLON.Matrix = Matrix;
  3925. var Plane = (function () {
  3926. /**
  3927. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3928. */
  3929. function Plane(a, b, c, d) {
  3930. this.normal = new Vector3(a, b, c);
  3931. this.d = d;
  3932. }
  3933. /**
  3934. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3935. */
  3936. Plane.prototype.asArray = function () {
  3937. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3938. };
  3939. // Methods
  3940. /**
  3941. * Returns a new plane copied from the current Plane.
  3942. */
  3943. Plane.prototype.clone = function () {
  3944. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3945. };
  3946. /**
  3947. * Returns the string "Plane".
  3948. */
  3949. Plane.prototype.getClassName = function () {
  3950. return "Plane";
  3951. };
  3952. /**
  3953. * Returns the Plane hash code.
  3954. */
  3955. Plane.prototype.getHashCode = function () {
  3956. var hash = this.normal.getHashCode();
  3957. hash = (hash * 397) ^ (this.d || 0);
  3958. return hash;
  3959. };
  3960. /**
  3961. * Normalize the current Plane in place.
  3962. * Returns the updated Plane.
  3963. */
  3964. Plane.prototype.normalize = function () {
  3965. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3966. var magnitude = 0.0;
  3967. if (norm !== 0) {
  3968. magnitude = 1.0 / norm;
  3969. }
  3970. this.normal.x *= magnitude;
  3971. this.normal.y *= magnitude;
  3972. this.normal.z *= magnitude;
  3973. this.d *= magnitude;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3978. */
  3979. Plane.prototype.transform = function (transformation) {
  3980. var transposedMatrix = Matrix.Transpose(transformation);
  3981. var x = this.normal.x;
  3982. var y = this.normal.y;
  3983. var z = this.normal.z;
  3984. var d = this.d;
  3985. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3986. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3987. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3988. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3989. return new Plane(normalX, normalY, normalZ, finalD);
  3990. };
  3991. /**
  3992. * Returns the dot product (float) of the point coordinates and the plane normal.
  3993. */
  3994. Plane.prototype.dotCoordinate = function (point) {
  3995. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3996. };
  3997. /**
  3998. * Updates the current Plane from the plane defined by the three passed points.
  3999. * Returns the updated Plane.
  4000. */
  4001. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4002. var x1 = point2.x - point1.x;
  4003. var y1 = point2.y - point1.y;
  4004. var z1 = point2.z - point1.z;
  4005. var x2 = point3.x - point1.x;
  4006. var y2 = point3.y - point1.y;
  4007. var z2 = point3.z - point1.z;
  4008. var yz = (y1 * z2) - (z1 * y2);
  4009. var xz = (z1 * x2) - (x1 * z2);
  4010. var xy = (x1 * y2) - (y1 * x2);
  4011. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4012. var invPyth;
  4013. if (pyth !== 0) {
  4014. invPyth = 1.0 / pyth;
  4015. }
  4016. else {
  4017. invPyth = 0.0;
  4018. }
  4019. this.normal.x = yz * invPyth;
  4020. this.normal.y = xz * invPyth;
  4021. this.normal.z = xy * invPyth;
  4022. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4023. return this;
  4024. };
  4025. /**
  4026. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4027. */
  4028. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4029. var dot = Vector3.Dot(this.normal, direction);
  4030. return (dot <= epsilon);
  4031. };
  4032. /**
  4033. * Returns the signed distance (float) from the passed point to the Plane.
  4034. */
  4035. Plane.prototype.signedDistanceTo = function (point) {
  4036. return Vector3.Dot(point, this.normal) + this.d;
  4037. };
  4038. // Statics
  4039. /**
  4040. * Returns a new Plane from the passed array.
  4041. */
  4042. Plane.FromArray = function (array) {
  4043. return new Plane(array[0], array[1], array[2], array[3]);
  4044. };
  4045. /**
  4046. * Returns a new Plane defined by the three passed points.
  4047. */
  4048. Plane.FromPoints = function (point1, point2, point3) {
  4049. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4050. result.copyFromPoints(point1, point2, point3);
  4051. return result;
  4052. };
  4053. /**
  4054. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4055. * Note : the vector "normal" is updated because normalized.
  4056. */
  4057. Plane.FromPositionAndNormal = function (origin, normal) {
  4058. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4059. normal.normalize();
  4060. result.normal = normal;
  4061. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4062. return result;
  4063. };
  4064. /**
  4065. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4066. */
  4067. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4068. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4069. return Vector3.Dot(point, normal) + d;
  4070. };
  4071. return Plane;
  4072. }());
  4073. BABYLON.Plane = Plane;
  4074. var Viewport = (function () {
  4075. /**
  4076. * Creates a Viewport object located at (x, y) and sized (width, height).
  4077. */
  4078. function Viewport(x, y, width, height) {
  4079. this.x = x;
  4080. this.y = y;
  4081. this.width = width;
  4082. this.height = height;
  4083. }
  4084. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4085. if (renderWidthOrEngine._gl) {
  4086. var engine = renderWidthOrEngine;
  4087. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4088. }
  4089. var renderWidth = renderWidthOrEngine;
  4090. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4091. };
  4092. /**
  4093. * Returns a new Viewport copied from the current one.
  4094. */
  4095. Viewport.prototype.clone = function () {
  4096. return new Viewport(this.x, this.y, this.width, this.height);
  4097. };
  4098. return Viewport;
  4099. }());
  4100. BABYLON.Viewport = Viewport;
  4101. var Frustum = (function () {
  4102. function Frustum() {
  4103. }
  4104. /**
  4105. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4106. */
  4107. Frustum.GetPlanes = function (transform) {
  4108. var frustumPlanes = [];
  4109. for (var index = 0; index < 6; index++) {
  4110. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4111. }
  4112. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4113. return frustumPlanes;
  4114. };
  4115. /**
  4116. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4117. */
  4118. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4119. // Near
  4120. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4121. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4122. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4123. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4124. frustumPlanes[0].normalize();
  4125. // Far
  4126. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4127. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4128. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4129. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4130. frustumPlanes[1].normalize();
  4131. // Left
  4132. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4133. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4134. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4135. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4136. frustumPlanes[2].normalize();
  4137. // Right
  4138. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4139. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4140. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4141. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4142. frustumPlanes[3].normalize();
  4143. // Top
  4144. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4145. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4146. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4147. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4148. frustumPlanes[4].normalize();
  4149. // Bottom
  4150. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4151. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4152. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4153. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4154. frustumPlanes[5].normalize();
  4155. };
  4156. return Frustum;
  4157. }());
  4158. BABYLON.Frustum = Frustum;
  4159. var Space;
  4160. (function (Space) {
  4161. Space[Space["LOCAL"] = 0] = "LOCAL";
  4162. Space[Space["WORLD"] = 1] = "WORLD";
  4163. Space[Space["BONE"] = 2] = "BONE";
  4164. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4165. var Axis = (function () {
  4166. function Axis() {
  4167. }
  4168. return Axis;
  4169. }());
  4170. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4171. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4172. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4173. BABYLON.Axis = Axis;
  4174. ;
  4175. var BezierCurve = (function () {
  4176. function BezierCurve() {
  4177. }
  4178. /**
  4179. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4180. */
  4181. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4182. // Extract X (which is equal to time here)
  4183. var f0 = 1 - 3 * x2 + 3 * x1;
  4184. var f1 = 3 * x2 - 6 * x1;
  4185. var f2 = 3 * x1;
  4186. var refinedT = t;
  4187. for (var i = 0; i < 5; i++) {
  4188. var refinedT2 = refinedT * refinedT;
  4189. var refinedT3 = refinedT2 * refinedT;
  4190. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4191. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4192. refinedT -= (x - t) * slope;
  4193. refinedT = Math.min(1, Math.max(0, refinedT));
  4194. }
  4195. // Resolve cubic bezier for the given x
  4196. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4197. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4198. Math.pow(refinedT, 3);
  4199. };
  4200. return BezierCurve;
  4201. }());
  4202. BABYLON.BezierCurve = BezierCurve;
  4203. var Orientation;
  4204. (function (Orientation) {
  4205. Orientation[Orientation["CW"] = 0] = "CW";
  4206. Orientation[Orientation["CCW"] = 1] = "CCW";
  4207. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4208. var Angle = (function () {
  4209. /**
  4210. * Creates an Angle object of "radians" radians (float).
  4211. */
  4212. function Angle(radians) {
  4213. var _this = this;
  4214. /**
  4215. * Returns the Angle value in degrees (float).
  4216. */
  4217. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4218. /**
  4219. * Returns the Angle value in radians (float).
  4220. */
  4221. this.radians = function () { return _this._radians; };
  4222. this._radians = radians;
  4223. if (this._radians < 0.0)
  4224. this._radians += (2.0 * Math.PI);
  4225. }
  4226. /**
  4227. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4228. */
  4229. Angle.BetweenTwoPoints = function (a, b) {
  4230. var delta = b.subtract(a);
  4231. var theta = Math.atan2(delta.y, delta.x);
  4232. return new Angle(theta);
  4233. };
  4234. /**
  4235. * Returns a new Angle object from the passed float in radians.
  4236. */
  4237. Angle.FromRadians = function (radians) {
  4238. return new Angle(radians);
  4239. };
  4240. /**
  4241. * Returns a new Angle object from the passed float in degrees.
  4242. */
  4243. Angle.FromDegrees = function (degrees) {
  4244. return new Angle(degrees * Math.PI / 180.0);
  4245. };
  4246. return Angle;
  4247. }());
  4248. BABYLON.Angle = Angle;
  4249. var Arc2 = (function () {
  4250. /**
  4251. * Creates an Arc object from the three passed points : start, middle and end.
  4252. */
  4253. function Arc2(startPoint, midPoint, endPoint) {
  4254. this.startPoint = startPoint;
  4255. this.midPoint = midPoint;
  4256. this.endPoint = endPoint;
  4257. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4258. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4259. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4260. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4261. 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);
  4262. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4263. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4264. var a1 = this.startAngle.degrees();
  4265. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4266. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4267. // angles correction
  4268. if (a2 - a1 > +180.0)
  4269. a2 -= 360.0;
  4270. if (a2 - a1 < -180.0)
  4271. a2 += 360.0;
  4272. if (a3 - a2 > +180.0)
  4273. a3 -= 360.0;
  4274. if (a3 - a2 < -180.0)
  4275. a3 += 360.0;
  4276. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4277. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4278. }
  4279. return Arc2;
  4280. }());
  4281. BABYLON.Arc2 = Arc2;
  4282. var Path2 = (function () {
  4283. /**
  4284. * Creates a Path2 object from the starting 2D coordinates x and y.
  4285. */
  4286. function Path2(x, y) {
  4287. this._points = new Array();
  4288. this._length = 0.0;
  4289. this.closed = false;
  4290. this._points.push(new Vector2(x, y));
  4291. }
  4292. /**
  4293. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4294. * Returns the updated Path2.
  4295. */
  4296. Path2.prototype.addLineTo = function (x, y) {
  4297. if (closed) {
  4298. //Tools.Error("cannot add lines to closed paths");
  4299. return this;
  4300. }
  4301. var newPoint = new Vector2(x, y);
  4302. var previousPoint = this._points[this._points.length - 1];
  4303. this._points.push(newPoint);
  4304. this._length += newPoint.subtract(previousPoint).length();
  4305. return this;
  4306. };
  4307. /**
  4308. * 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.
  4309. * Returns the updated Path2.
  4310. */
  4311. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4312. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4313. if (closed) {
  4314. //Tools.Error("cannot add arcs to closed paths");
  4315. return this;
  4316. }
  4317. var startPoint = this._points[this._points.length - 1];
  4318. var midPoint = new Vector2(midX, midY);
  4319. var endPoint = new Vector2(endX, endY);
  4320. var arc = new Arc2(startPoint, midPoint, endPoint);
  4321. var increment = arc.angle.radians() / numberOfSegments;
  4322. if (arc.orientation === Orientation.CW)
  4323. increment *= -1;
  4324. var currentAngle = arc.startAngle.radians() + increment;
  4325. for (var i = 0; i < numberOfSegments; i++) {
  4326. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4327. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4328. this.addLineTo(x, y);
  4329. currentAngle += increment;
  4330. }
  4331. return this;
  4332. };
  4333. /**
  4334. * Closes the Path2.
  4335. * Returns the Path2.
  4336. */
  4337. Path2.prototype.close = function () {
  4338. this.closed = true;
  4339. return this;
  4340. };
  4341. /**
  4342. * Returns the Path2 total length (float).
  4343. */
  4344. Path2.prototype.length = function () {
  4345. var result = this._length;
  4346. if (!this.closed) {
  4347. var lastPoint = this._points[this._points.length - 1];
  4348. var firstPoint = this._points[0];
  4349. result += (firstPoint.subtract(lastPoint).length());
  4350. }
  4351. return result;
  4352. };
  4353. /**
  4354. * Returns the Path2 internal array of points.
  4355. */
  4356. Path2.prototype.getPoints = function () {
  4357. return this._points;
  4358. };
  4359. /**
  4360. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4361. */
  4362. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4363. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4364. //Tools.Error("normalized length position should be between 0 and 1.");
  4365. return Vector2.Zero();
  4366. }
  4367. var lengthPosition = normalizedLengthPosition * this.length();
  4368. var previousOffset = 0;
  4369. for (var i = 0; i < this._points.length; i++) {
  4370. var j = (i + 1) % this._points.length;
  4371. var a = this._points[i];
  4372. var b = this._points[j];
  4373. var bToA = b.subtract(a);
  4374. var nextOffset = (bToA.length() + previousOffset);
  4375. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4376. var dir = bToA.normalize();
  4377. var localOffset = lengthPosition - previousOffset;
  4378. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4379. }
  4380. previousOffset = nextOffset;
  4381. }
  4382. //Tools.Error("internal error");
  4383. return Vector2.Zero();
  4384. };
  4385. /**
  4386. * Returns a new Path2 starting at the coordinates (x, y).
  4387. */
  4388. Path2.StartingAt = function (x, y) {
  4389. return new Path2(x, y);
  4390. };
  4391. return Path2;
  4392. }());
  4393. BABYLON.Path2 = Path2;
  4394. var Path3D = (function () {
  4395. /**
  4396. * new Path3D(path, normal, raw)
  4397. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4398. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4399. * path : an array of Vector3, the curve axis of the Path3D
  4400. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4401. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4402. */
  4403. function Path3D(path, firstNormal, raw) {
  4404. this.path = path;
  4405. this._curve = new Array();
  4406. this._distances = new Array();
  4407. this._tangents = new Array();
  4408. this._normals = new Array();
  4409. this._binormals = new Array();
  4410. for (var p = 0; p < path.length; p++) {
  4411. this._curve[p] = path[p].clone(); // hard copy
  4412. }
  4413. this._raw = raw || false;
  4414. this._compute(firstNormal);
  4415. }
  4416. /**
  4417. * Returns the Path3D array of successive Vector3 designing its curve.
  4418. */
  4419. Path3D.prototype.getCurve = function () {
  4420. return this._curve;
  4421. };
  4422. /**
  4423. * Returns an array populated with tangent vectors on each Path3D curve point.
  4424. */
  4425. Path3D.prototype.getTangents = function () {
  4426. return this._tangents;
  4427. };
  4428. /**
  4429. * Returns an array populated with normal vectors on each Path3D curve point.
  4430. */
  4431. Path3D.prototype.getNormals = function () {
  4432. return this._normals;
  4433. };
  4434. /**
  4435. * Returns an array populated with binormal vectors on each Path3D curve point.
  4436. */
  4437. Path3D.prototype.getBinormals = function () {
  4438. return this._binormals;
  4439. };
  4440. /**
  4441. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4442. */
  4443. Path3D.prototype.getDistances = function () {
  4444. return this._distances;
  4445. };
  4446. /**
  4447. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4448. * Returns the same object updated.
  4449. */
  4450. Path3D.prototype.update = function (path, firstNormal) {
  4451. for (var p = 0; p < path.length; p++) {
  4452. this._curve[p].x = path[p].x;
  4453. this._curve[p].y = path[p].y;
  4454. this._curve[p].z = path[p].z;
  4455. }
  4456. this._compute(firstNormal);
  4457. return this;
  4458. };
  4459. // private function compute() : computes tangents, normals and binormals
  4460. Path3D.prototype._compute = function (firstNormal) {
  4461. var l = this._curve.length;
  4462. // first and last tangents
  4463. this._tangents[0] = this._getFirstNonNullVector(0);
  4464. if (!this._raw) {
  4465. this._tangents[0].normalize();
  4466. }
  4467. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4468. if (!this._raw) {
  4469. this._tangents[l - 1].normalize();
  4470. }
  4471. // normals and binormals at first point : arbitrary vector with _normalVector()
  4472. var tg0 = this._tangents[0];
  4473. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4474. this._normals[0] = pp0;
  4475. if (!this._raw) {
  4476. this._normals[0].normalize();
  4477. }
  4478. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4479. if (!this._raw) {
  4480. this._binormals[0].normalize();
  4481. }
  4482. this._distances[0] = 0.0;
  4483. // normals and binormals : next points
  4484. var prev; // previous vector (segment)
  4485. var cur; // current vector (segment)
  4486. var curTang; // current tangent
  4487. // previous normal
  4488. var prevBinor; // previous binormal
  4489. for (var i = 1; i < l; i++) {
  4490. // tangents
  4491. prev = this._getLastNonNullVector(i);
  4492. if (i < l - 1) {
  4493. cur = this._getFirstNonNullVector(i);
  4494. this._tangents[i] = prev.add(cur);
  4495. this._tangents[i].normalize();
  4496. }
  4497. this._distances[i] = this._distances[i - 1] + prev.length();
  4498. // normals and binormals
  4499. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4500. curTang = this._tangents[i];
  4501. prevBinor = this._binormals[i - 1];
  4502. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4503. if (!this._raw) {
  4504. this._normals[i].normalize();
  4505. }
  4506. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4507. if (!this._raw) {
  4508. this._binormals[i].normalize();
  4509. }
  4510. }
  4511. };
  4512. // private function getFirstNonNullVector(index)
  4513. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4514. Path3D.prototype._getFirstNonNullVector = function (index) {
  4515. var i = 1;
  4516. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4517. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4518. i++;
  4519. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4520. }
  4521. return nNVector;
  4522. };
  4523. // private function getLastNonNullVector(index)
  4524. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4525. Path3D.prototype._getLastNonNullVector = function (index) {
  4526. var i = 1;
  4527. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4528. while (nLVector.length() === 0 && index > i + 1) {
  4529. i++;
  4530. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4531. }
  4532. return nLVector;
  4533. };
  4534. // private function normalVector(v0, vt, va) :
  4535. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4536. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4537. Path3D.prototype._normalVector = function (v0, vt, va) {
  4538. var normal0;
  4539. var tgl = vt.length();
  4540. if (tgl === 0.0) {
  4541. tgl = 1.0;
  4542. }
  4543. if (va === undefined || va === null) {
  4544. var point;
  4545. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4546. point = new Vector3(0.0, -1.0, 0.0);
  4547. }
  4548. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4549. point = new Vector3(1.0, 0.0, 0.0);
  4550. }
  4551. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4552. point = new Vector3(0.0, 0.0, 1.0);
  4553. }
  4554. normal0 = Vector3.Cross(vt, point);
  4555. }
  4556. else {
  4557. normal0 = Vector3.Cross(vt, va);
  4558. Vector3.CrossToRef(normal0, vt, normal0);
  4559. }
  4560. normal0.normalize();
  4561. return normal0;
  4562. };
  4563. return Path3D;
  4564. }());
  4565. BABYLON.Path3D = Path3D;
  4566. var Curve3 = (function () {
  4567. /**
  4568. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4569. * A Curve3 is designed from a series of successive Vector3.
  4570. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4571. */
  4572. function Curve3(points) {
  4573. this._length = 0.0;
  4574. this._points = points;
  4575. this._length = this._computeLength(points);
  4576. }
  4577. /**
  4578. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4579. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4580. * @param v1 (Vector3) the control point
  4581. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4582. * @param nbPoints (integer) the wanted number of points in the curve
  4583. */
  4584. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4585. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4586. var bez = new Array();
  4587. var equation = function (t, val0, val1, val2) {
  4588. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4589. return res;
  4590. };
  4591. for (var i = 0; i <= nbPoints; i++) {
  4592. 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)));
  4593. }
  4594. return new Curve3(bez);
  4595. };
  4596. /**
  4597. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4598. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4599. * @param v1 (Vector3) the first control point
  4600. * @param v2 (Vector3) the second control point
  4601. * @param v3 (Vector3) the end point of the Cubic Bezier
  4602. * @param nbPoints (integer) the wanted number of points in the curve
  4603. */
  4604. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4605. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4606. var bez = new Array();
  4607. var equation = function (t, val0, val1, val2, val3) {
  4608. 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;
  4609. return res;
  4610. };
  4611. for (var i = 0; i <= nbPoints; i++) {
  4612. 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)));
  4613. }
  4614. return new Curve3(bez);
  4615. };
  4616. /**
  4617. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4618. * @param p1 (Vector3) the origin point of the Hermite Spline
  4619. * @param t1 (Vector3) the tangent vector at the origin point
  4620. * @param p2 (Vector3) the end point of the Hermite Spline
  4621. * @param t2 (Vector3) the tangent vector at the end point
  4622. * @param nbPoints (integer) the wanted number of points in the curve
  4623. */
  4624. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4625. var hermite = new Array();
  4626. var step = 1.0 / nbPoints;
  4627. for (var i = 0; i <= nbPoints; i++) {
  4628. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4629. }
  4630. return new Curve3(hermite);
  4631. };
  4632. /**
  4633. * Returns a Curve3 object along a CatmullRom Spline curve :
  4634. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4635. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4636. */
  4637. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4638. var totalPoints = new Array();
  4639. totalPoints.push(points[0].clone());
  4640. Array.prototype.push.apply(totalPoints, points);
  4641. totalPoints.push(points[points.length - 1].clone());
  4642. var catmullRom = new Array();
  4643. var step = 1.0 / nbPoints;
  4644. for (var i = 0; i < totalPoints.length - 3; i++) {
  4645. var amount = 0.0;
  4646. for (var c = 0; c < nbPoints; c++) {
  4647. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4648. amount += step;
  4649. }
  4650. }
  4651. i--;
  4652. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4653. return new Curve3(catmullRom);
  4654. };
  4655. /**
  4656. * Returns the Curve3 stored array of successive Vector3
  4657. */
  4658. Curve3.prototype.getPoints = function () {
  4659. return this._points;
  4660. };
  4661. /**
  4662. * Returns the computed length (float) of the curve.
  4663. */
  4664. Curve3.prototype.length = function () {
  4665. return this._length;
  4666. };
  4667. /**
  4668. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4669. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4670. * curveA and curveB keep unchanged.
  4671. */
  4672. Curve3.prototype.continue = function (curve) {
  4673. var lastPoint = this._points[this._points.length - 1];
  4674. var continuedPoints = this._points.slice();
  4675. var curvePoints = curve.getPoints();
  4676. for (var i = 1; i < curvePoints.length; i++) {
  4677. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4678. }
  4679. var continuedCurve = new Curve3(continuedPoints);
  4680. return continuedCurve;
  4681. };
  4682. Curve3.prototype._computeLength = function (path) {
  4683. var l = 0;
  4684. for (var i = 1; i < path.length; i++) {
  4685. l += (path[i].subtract(path[i - 1])).length();
  4686. }
  4687. return l;
  4688. };
  4689. return Curve3;
  4690. }());
  4691. BABYLON.Curve3 = Curve3;
  4692. // Vertex formats
  4693. var PositionNormalVertex = (function () {
  4694. function PositionNormalVertex(position, normal) {
  4695. if (position === void 0) { position = Vector3.Zero(); }
  4696. if (normal === void 0) { normal = Vector3.Up(); }
  4697. this.position = position;
  4698. this.normal = normal;
  4699. }
  4700. PositionNormalVertex.prototype.clone = function () {
  4701. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4702. };
  4703. return PositionNormalVertex;
  4704. }());
  4705. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4706. var PositionNormalTextureVertex = (function () {
  4707. function PositionNormalTextureVertex(position, normal, uv) {
  4708. if (position === void 0) { position = Vector3.Zero(); }
  4709. if (normal === void 0) { normal = Vector3.Up(); }
  4710. if (uv === void 0) { uv = Vector2.Zero(); }
  4711. this.position = position;
  4712. this.normal = normal;
  4713. this.uv = uv;
  4714. }
  4715. PositionNormalTextureVertex.prototype.clone = function () {
  4716. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4717. };
  4718. return PositionNormalTextureVertex;
  4719. }());
  4720. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4721. // Temporary pre-allocated objects for engine internal use
  4722. // usage in any internal function :
  4723. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4724. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4725. var Tmp = (function () {
  4726. function Tmp() {
  4727. }
  4728. return Tmp;
  4729. }());
  4730. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4731. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4732. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4733. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4734. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4735. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4736. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4737. Matrix.Zero(), Matrix.Zero(),
  4738. Matrix.Zero(), Matrix.Zero(),
  4739. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4740. BABYLON.Tmp = Tmp;
  4741. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4742. var MathTmp = (function () {
  4743. function MathTmp() {
  4744. }
  4745. return MathTmp;
  4746. }());
  4747. MathTmp.Vector3 = [Vector3.Zero()];
  4748. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4749. MathTmp.Quaternion = [Quaternion.Zero()];
  4750. })(BABYLON || (BABYLON = {}));
  4751. //# sourceMappingURL=babylon.math.js.map
  4752. //# sourceMappingURL=babylon.mixins.js.map
  4753. var BABYLON;
  4754. (function (BABYLON) {
  4755. function generateSerializableMember(type, sourceName) {
  4756. return function (target, propertyKey) {
  4757. if (!target.__serializableMembers) {
  4758. target.__serializableMembers = {};
  4759. }
  4760. if (!target.__serializableMembers[propertyKey]) {
  4761. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4762. }
  4763. };
  4764. }
  4765. function generateExpandMember(setCallback, targetKey) {
  4766. return function (target, propertyKey) {
  4767. var key = targetKey || ("_" + propertyKey);
  4768. Object.defineProperty(target, propertyKey, {
  4769. get: function () {
  4770. return this[key];
  4771. },
  4772. set: function (value) {
  4773. if (this[key] === value) {
  4774. return;
  4775. }
  4776. this[key] = value;
  4777. target[setCallback].apply(this);
  4778. },
  4779. enumerable: true,
  4780. configurable: true
  4781. });
  4782. };
  4783. }
  4784. function expandToProperty(callback, targetKey) {
  4785. return generateExpandMember(callback, targetKey);
  4786. }
  4787. BABYLON.expandToProperty = expandToProperty;
  4788. function serialize(sourceName) {
  4789. return generateSerializableMember(0, sourceName); // value member
  4790. }
  4791. BABYLON.serialize = serialize;
  4792. function serializeAsTexture(sourceName) {
  4793. return generateSerializableMember(1, sourceName); // texture member
  4794. }
  4795. BABYLON.serializeAsTexture = serializeAsTexture;
  4796. function serializeAsColor3(sourceName) {
  4797. return generateSerializableMember(2, sourceName); // color3 member
  4798. }
  4799. BABYLON.serializeAsColor3 = serializeAsColor3;
  4800. function serializeAsFresnelParameters(sourceName) {
  4801. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4802. }
  4803. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4804. function serializeAsVector2(sourceName) {
  4805. return generateSerializableMember(4, sourceName); // vector2 member
  4806. }
  4807. BABYLON.serializeAsVector2 = serializeAsVector2;
  4808. function serializeAsVector3(sourceName) {
  4809. return generateSerializableMember(5, sourceName); // vector3 member
  4810. }
  4811. BABYLON.serializeAsVector3 = serializeAsVector3;
  4812. function serializeAsMeshReference(sourceName) {
  4813. return generateSerializableMember(6, sourceName); // mesh reference member
  4814. }
  4815. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4816. function serializeAsColorCurves(sourceName) {
  4817. return generateSerializableMember(7, sourceName); // color curves
  4818. }
  4819. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4820. function serializeAsColor4(sourceName) {
  4821. return generateSerializableMember(8, sourceName); // color 4
  4822. }
  4823. BABYLON.serializeAsColor4 = serializeAsColor4;
  4824. function serializeAsImageProcessingConfiguration(sourceName) {
  4825. return generateSerializableMember(9, sourceName); // image processing
  4826. }
  4827. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  4828. var SerializationHelper = (function () {
  4829. function SerializationHelper() {
  4830. }
  4831. SerializationHelper.Serialize = function (entity, serializationObject) {
  4832. if (!serializationObject) {
  4833. serializationObject = {};
  4834. }
  4835. // Tags
  4836. if (BABYLON.Tags) {
  4837. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4838. }
  4839. // Properties
  4840. for (var property in entity.__serializableMembers) {
  4841. var propertyDescriptor = entity.__serializableMembers[property];
  4842. var targetPropertyName = propertyDescriptor.sourceName || property;
  4843. var propertyType = propertyDescriptor.type;
  4844. var sourceProperty = entity[property];
  4845. if (sourceProperty !== undefined && sourceProperty !== null) {
  4846. switch (propertyType) {
  4847. case 0:
  4848. serializationObject[targetPropertyName] = sourceProperty;
  4849. break;
  4850. case 1:
  4851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4852. break;
  4853. case 2:
  4854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4855. break;
  4856. case 3:
  4857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4858. break;
  4859. case 4:
  4860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4861. break;
  4862. case 5:
  4863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4864. break;
  4865. case 6:
  4866. serializationObject[targetPropertyName] = sourceProperty.id;
  4867. break;
  4868. case 7:
  4869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4870. break;
  4871. case 8:
  4872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4873. break;
  4874. case 9:
  4875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4876. break;
  4877. }
  4878. }
  4879. }
  4880. return serializationObject;
  4881. };
  4882. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4883. var destination = creationFunction();
  4884. // Tags
  4885. if (BABYLON.Tags) {
  4886. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4887. }
  4888. // Properties
  4889. for (var property in destination.__serializableMembers) {
  4890. var propertyDescriptor = destination.__serializableMembers[property];
  4891. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4892. var propertyType = propertyDescriptor.type;
  4893. if (sourceProperty !== undefined && sourceProperty !== null) {
  4894. switch (propertyType) {
  4895. case 0:
  4896. destination[property] = sourceProperty;
  4897. break;
  4898. case 1:
  4899. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4900. break;
  4901. case 2:
  4902. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4903. break;
  4904. case 3:
  4905. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4906. break;
  4907. case 4:
  4908. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4909. break;
  4910. case 5:
  4911. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4912. break;
  4913. case 6:
  4914. destination[property] = scene.getLastMeshByID(sourceProperty);
  4915. break;
  4916. case 7:
  4917. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4918. break;
  4919. case 8:
  4920. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  4921. break;
  4922. case 9:
  4923. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  4924. break;
  4925. }
  4926. }
  4927. }
  4928. return destination;
  4929. };
  4930. SerializationHelper.Clone = function (creationFunction, source) {
  4931. var destination = creationFunction();
  4932. // Tags
  4933. if (BABYLON.Tags) {
  4934. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4935. }
  4936. // Properties
  4937. for (var property in destination.__serializableMembers) {
  4938. var propertyDescriptor = destination.__serializableMembers[property];
  4939. var sourceProperty = source[property];
  4940. var propertyType = propertyDescriptor.type;
  4941. if (sourceProperty !== undefined && sourceProperty !== null) {
  4942. switch (propertyType) {
  4943. case 0: // Value
  4944. case 6:
  4945. destination[property] = sourceProperty;
  4946. break;
  4947. case 1: // Texture
  4948. case 2: // Color3
  4949. case 3: // FresnelParameters
  4950. case 4: // Vector2
  4951. case 5: // Vector3
  4952. case 7:
  4953. destination[property] = sourceProperty.clone();
  4954. break;
  4955. }
  4956. }
  4957. }
  4958. return destination;
  4959. };
  4960. return SerializationHelper;
  4961. }());
  4962. BABYLON.SerializationHelper = SerializationHelper;
  4963. })(BABYLON || (BABYLON = {}));
  4964. //# sourceMappingURL=babylon.decorators.js.map
  4965. var BABYLON;
  4966. (function (BABYLON) {
  4967. /**
  4968. * A class serves as a medium between the observable and its observers
  4969. */
  4970. var EventState = (function () {
  4971. /**
  4972. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4973. */
  4974. function EventState(mask, skipNextObservers) {
  4975. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4976. this.initalize(mask, skipNextObservers);
  4977. }
  4978. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4979. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4980. this.mask = mask;
  4981. this.skipNextObservers = skipNextObservers;
  4982. return this;
  4983. };
  4984. return EventState;
  4985. }());
  4986. BABYLON.EventState = EventState;
  4987. /**
  4988. * Represent an Observer registered to a given Observable object.
  4989. */
  4990. var Observer = (function () {
  4991. function Observer(callback, mask) {
  4992. this.callback = callback;
  4993. this.mask = mask;
  4994. }
  4995. return Observer;
  4996. }());
  4997. BABYLON.Observer = Observer;
  4998. /**
  4999. * The Observable class is a simple implementation of the Observable pattern.
  5000. * 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.
  5001. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5002. * 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).
  5003. * 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.
  5004. */
  5005. var Observable = (function () {
  5006. function Observable() {
  5007. this._observers = new Array();
  5008. this._eventState = new EventState(0);
  5009. }
  5010. /**
  5011. * Create a new Observer with the specified callback
  5012. * @param callback the callback that will be executed for that Observer
  5013. * @param mask the mask used to filter observers
  5014. * @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.
  5015. */
  5016. Observable.prototype.add = function (callback, mask, insertFirst) {
  5017. if (mask === void 0) { mask = -1; }
  5018. if (insertFirst === void 0) { insertFirst = false; }
  5019. if (!callback) {
  5020. return null;
  5021. }
  5022. var observer = new Observer(callback, mask);
  5023. if (insertFirst) {
  5024. this._observers.unshift(observer);
  5025. }
  5026. else {
  5027. this._observers.push(observer);
  5028. }
  5029. return observer;
  5030. };
  5031. /**
  5032. * Remove an Observer from the Observable object
  5033. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5034. */
  5035. Observable.prototype.remove = function (observer) {
  5036. var index = this._observers.indexOf(observer);
  5037. if (index !== -1) {
  5038. this._observers.splice(index, 1);
  5039. return true;
  5040. }
  5041. return false;
  5042. };
  5043. /**
  5044. * Remove a callback from the Observable object
  5045. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5046. */
  5047. Observable.prototype.removeCallback = function (callback) {
  5048. for (var index = 0; index < this._observers.length; index++) {
  5049. if (this._observers[index].callback === callback) {
  5050. this._observers.splice(index, 1);
  5051. return true;
  5052. }
  5053. }
  5054. return false;
  5055. };
  5056. /**
  5057. * Notify all Observers by calling their respective callback with the given data
  5058. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5059. * @param eventData
  5060. * @param mask
  5061. */
  5062. Observable.prototype.notifyObservers = function (eventData, mask) {
  5063. if (mask === void 0) { mask = -1; }
  5064. var state = this._eventState;
  5065. state.mask = mask;
  5066. state.skipNextObservers = false;
  5067. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5068. var obs = _a[_i];
  5069. if (obs.mask & mask) {
  5070. obs.callback(eventData, state);
  5071. }
  5072. if (state.skipNextObservers) {
  5073. return false;
  5074. }
  5075. }
  5076. return true;
  5077. };
  5078. /**
  5079. * return true is the Observable has at least one Observer registered
  5080. */
  5081. Observable.prototype.hasObservers = function () {
  5082. return this._observers.length > 0;
  5083. };
  5084. /**
  5085. * Clear the list of observers
  5086. */
  5087. Observable.prototype.clear = function () {
  5088. this._observers = new Array();
  5089. };
  5090. /**
  5091. * Clone the current observable
  5092. */
  5093. Observable.prototype.clone = function () {
  5094. var result = new Observable();
  5095. result._observers = this._observers.slice(0);
  5096. return result;
  5097. };
  5098. /**
  5099. * Does this observable handles observer registered with a given mask
  5100. * @param {number} trigger - the mask to be tested
  5101. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5102. **/
  5103. Observable.prototype.hasSpecificMask = function (mask) {
  5104. if (mask === void 0) { mask = -1; }
  5105. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5106. var obs = _a[_i];
  5107. if (obs.mask & mask && obs.mask === mask) {
  5108. return true;
  5109. }
  5110. }
  5111. return false;
  5112. };
  5113. return Observable;
  5114. }());
  5115. BABYLON.Observable = Observable;
  5116. })(BABYLON || (BABYLON = {}));
  5117. //# sourceMappingURL=babylon.observable.js.map
  5118. var BABYLON;
  5119. (function (BABYLON) {
  5120. var SmartArray = (function () {
  5121. function SmartArray(capacity) {
  5122. this.length = 0;
  5123. this._duplicateId = 0;
  5124. this.data = new Array(capacity);
  5125. this._id = SmartArray._GlobalId++;
  5126. }
  5127. SmartArray.prototype.push = function (value) {
  5128. this.data[this.length++] = value;
  5129. if (this.length > this.data.length) {
  5130. this.data.length *= 2;
  5131. }
  5132. if (!value.__smartArrayFlags) {
  5133. value.__smartArrayFlags = {};
  5134. }
  5135. value.__smartArrayFlags[this._id] = this._duplicateId;
  5136. };
  5137. SmartArray.prototype.forEach = function (func) {
  5138. for (var index = 0; index < this.length; index++) {
  5139. func(this.data[index]);
  5140. }
  5141. };
  5142. SmartArray.prototype.pushNoDuplicate = function (value) {
  5143. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5144. return false;
  5145. }
  5146. this.push(value);
  5147. return true;
  5148. };
  5149. SmartArray.prototype.sort = function (compareFn) {
  5150. this.data.sort(compareFn);
  5151. };
  5152. SmartArray.prototype.reset = function () {
  5153. this.length = 0;
  5154. this._duplicateId++;
  5155. };
  5156. SmartArray.prototype.dispose = function () {
  5157. this.reset();
  5158. this.data.length = 0;
  5159. };
  5160. SmartArray.prototype.concat = function (array) {
  5161. if (array.length === 0) {
  5162. return;
  5163. }
  5164. if (this.length + array.length > this.data.length) {
  5165. this.data.length = (this.length + array.length) * 2;
  5166. }
  5167. for (var index = 0; index < array.length; index++) {
  5168. this.data[this.length++] = (array.data || array)[index];
  5169. }
  5170. };
  5171. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5172. if (array.length === 0) {
  5173. return;
  5174. }
  5175. if (this.length + array.length > this.data.length) {
  5176. this.data.length = (this.length + array.length) * 2;
  5177. }
  5178. for (var index = 0; index < array.length; index++) {
  5179. var item = (array.data || array)[index];
  5180. this.pushNoDuplicate(item);
  5181. }
  5182. };
  5183. SmartArray.prototype.indexOf = function (value) {
  5184. var position = this.data.indexOf(value);
  5185. if (position >= this.length) {
  5186. return -1;
  5187. }
  5188. return position;
  5189. };
  5190. SmartArray.prototype.contains = function (value) {
  5191. return this.data.indexOf(value) !== -1;
  5192. };
  5193. return SmartArray;
  5194. }());
  5195. // Statics
  5196. SmartArray._GlobalId = 0;
  5197. BABYLON.SmartArray = SmartArray;
  5198. })(BABYLON || (BABYLON = {}));
  5199. //# sourceMappingURL=babylon.smartArray.js.map
  5200. var BABYLON;
  5201. (function (BABYLON) {
  5202. // Screenshots
  5203. var screenshotCanvas;
  5204. var cloneValue = function (source, destinationObject) {
  5205. if (!source)
  5206. return null;
  5207. if (source instanceof BABYLON.Mesh) {
  5208. return null;
  5209. }
  5210. if (source instanceof BABYLON.SubMesh) {
  5211. return source.clone(destinationObject);
  5212. }
  5213. else if (source.clone) {
  5214. return source.clone();
  5215. }
  5216. return null;
  5217. };
  5218. var Tools = (function () {
  5219. function Tools() {
  5220. }
  5221. ;
  5222. /**
  5223. * Interpolates between a and b via alpha
  5224. * @param a The lower value (returned when alpha = 0)
  5225. * @param b The upper value (returned when alpha = 1)
  5226. * @param alpha The interpolation-factor
  5227. * @return The mixed value
  5228. */
  5229. Tools.Mix = function (a, b, alpha) {
  5230. return a * (1 - alpha) + b * alpha;
  5231. };
  5232. Tools.Instantiate = function (className) {
  5233. var arr = className.split(".");
  5234. var fn = (window || this);
  5235. for (var i = 0, len = arr.length; i < len; i++) {
  5236. fn = fn[arr[i]];
  5237. }
  5238. if (typeof fn !== "function") {
  5239. return null;
  5240. }
  5241. return fn;
  5242. };
  5243. Tools.SetImmediate = function (action) {
  5244. if (window.setImmediate) {
  5245. window.setImmediate(action);
  5246. }
  5247. else {
  5248. setTimeout(action, 1);
  5249. }
  5250. };
  5251. Tools.IsExponentOfTwo = function (value) {
  5252. var count = 1;
  5253. do {
  5254. count *= 2;
  5255. } while (count < value);
  5256. return count === value;
  5257. };
  5258. /**
  5259. * Find the next highest power of two.
  5260. * @param x Number to start search from.
  5261. * @return Next highest power of two.
  5262. */
  5263. Tools.CeilingPOT = function (x) {
  5264. x--;
  5265. x |= x >> 1;
  5266. x |= x >> 2;
  5267. x |= x >> 4;
  5268. x |= x >> 8;
  5269. x |= x >> 16;
  5270. x++;
  5271. return x;
  5272. };
  5273. /**
  5274. * Find the next lowest power of two.
  5275. * @param x Number to start search from.
  5276. * @return Next lowest power of two.
  5277. */
  5278. Tools.FloorPOT = function (x) {
  5279. x = x | (x >> 1);
  5280. x = x | (x >> 2);
  5281. x = x | (x >> 4);
  5282. x = x | (x >> 8);
  5283. x = x | (x >> 16);
  5284. return x - (x >> 1);
  5285. };
  5286. /**
  5287. * Find the nearest power of two.
  5288. * @param x Number to start search from.
  5289. * @return Next nearest power of two.
  5290. */
  5291. Tools.NearestPOT = function (x) {
  5292. var c = Tools.CeilingPOT(x);
  5293. var f = Tools.FloorPOT(x);
  5294. return (c - x) > (x - f) ? f : c;
  5295. };
  5296. Tools.GetExponentOfTwo = function (value, max, mode) {
  5297. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5298. var pot;
  5299. switch (mode) {
  5300. case BABYLON.Engine.SCALEMODE_FLOOR:
  5301. pot = Tools.FloorPOT(value);
  5302. break;
  5303. case BABYLON.Engine.SCALEMODE_NEAREST:
  5304. pot = Tools.NearestPOT(value);
  5305. break;
  5306. case BABYLON.Engine.SCALEMODE_CEILING:
  5307. pot = Tools.CeilingPOT(value);
  5308. break;
  5309. }
  5310. return Math.min(pot, max);
  5311. };
  5312. Tools.GetFilename = function (path) {
  5313. var index = path.lastIndexOf("/");
  5314. if (index < 0)
  5315. return path;
  5316. return path.substring(index + 1);
  5317. };
  5318. Tools.GetDOMTextContent = function (element) {
  5319. var result = "";
  5320. var child = element.firstChild;
  5321. while (child) {
  5322. if (child.nodeType === 3) {
  5323. result += child.textContent;
  5324. }
  5325. child = child.nextSibling;
  5326. }
  5327. return result;
  5328. };
  5329. Tools.ToDegrees = function (angle) {
  5330. return angle * 180 / Math.PI;
  5331. };
  5332. Tools.ToRadians = function (angle) {
  5333. return angle * Math.PI / 180;
  5334. };
  5335. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5336. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5337. var output = "";
  5338. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5339. var i = 0;
  5340. var bytes = new Uint8Array(buffer);
  5341. while (i < bytes.length) {
  5342. chr1 = bytes[i++];
  5343. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5344. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5345. enc1 = chr1 >> 2;
  5346. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5347. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5348. enc4 = chr3 & 63;
  5349. if (isNaN(chr2)) {
  5350. enc3 = enc4 = 64;
  5351. }
  5352. else if (isNaN(chr3)) {
  5353. enc4 = 64;
  5354. }
  5355. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5356. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5357. }
  5358. return "data:image/png;base64," + output;
  5359. };
  5360. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5361. if (bias === void 0) { bias = null; }
  5362. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5363. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5364. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5365. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5366. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5367. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5368. }
  5369. if (bias) {
  5370. minimum.x -= minimum.x * bias.x + bias.y;
  5371. minimum.y -= minimum.y * bias.x + bias.y;
  5372. minimum.z -= minimum.z * bias.x + bias.y;
  5373. maximum.x += maximum.x * bias.x + bias.y;
  5374. maximum.y += maximum.y * bias.x + bias.y;
  5375. maximum.z += maximum.z * bias.x + bias.y;
  5376. }
  5377. return {
  5378. minimum: minimum,
  5379. maximum: maximum
  5380. };
  5381. };
  5382. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5383. if (bias === void 0) { bias = null; }
  5384. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5385. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5386. if (!stride) {
  5387. stride = 3;
  5388. }
  5389. for (var index = start; index < start + count; index++) {
  5390. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5391. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5392. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5393. }
  5394. if (bias) {
  5395. minimum.x -= minimum.x * bias.x + bias.y;
  5396. minimum.y -= minimum.y * bias.x + bias.y;
  5397. minimum.z -= minimum.z * bias.x + bias.y;
  5398. maximum.x += maximum.x * bias.x + bias.y;
  5399. maximum.y += maximum.y * bias.x + bias.y;
  5400. maximum.z += maximum.z * bias.x + bias.y;
  5401. }
  5402. return {
  5403. minimum: minimum,
  5404. maximum: maximum
  5405. };
  5406. };
  5407. Tools.Vector2ArrayFeeder = function (array) {
  5408. return function (index) {
  5409. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5410. var length = isFloatArray ? array.length / 2 : array.length;
  5411. if (index >= length) {
  5412. return null;
  5413. }
  5414. if (isFloatArray) {
  5415. var fa = array;
  5416. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5417. }
  5418. var a = array;
  5419. return a[index];
  5420. };
  5421. };
  5422. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5423. if (bias === void 0) { bias = null; }
  5424. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5425. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5426. var i = 0;
  5427. var cur = feeder(i++);
  5428. while (cur) {
  5429. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5430. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5431. cur = feeder(i++);
  5432. }
  5433. if (bias) {
  5434. minimum.x -= minimum.x * bias.x + bias.y;
  5435. minimum.y -= minimum.y * bias.x + bias.y;
  5436. maximum.x += maximum.x * bias.x + bias.y;
  5437. maximum.y += maximum.y * bias.x + bias.y;
  5438. }
  5439. return {
  5440. minimum: minimum,
  5441. maximum: maximum
  5442. };
  5443. };
  5444. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5445. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5446. return undefined;
  5447. return Array.isArray(obj) ? obj : [obj];
  5448. };
  5449. // Misc.
  5450. Tools.GetPointerPrefix = function () {
  5451. var eventPrefix = "pointer";
  5452. // Check if pointer events are supported
  5453. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5454. eventPrefix = "mouse";
  5455. }
  5456. return eventPrefix;
  5457. };
  5458. /**
  5459. * @param func - the function to be called
  5460. * @param requester - the object that will request the next frame. Falls back to window.
  5461. */
  5462. Tools.QueueNewFrame = function (func, requester) {
  5463. if (requester === void 0) { requester = window; }
  5464. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5465. /*if(requester.isPresenting) {
  5466. return;
  5467. } else*/ if (requester.requestAnimationFrame)
  5468. requester.requestAnimationFrame(func);
  5469. else if (requester.msRequestAnimationFrame)
  5470. requester.msRequestAnimationFrame(func);
  5471. else if (requester.webkitRequestAnimationFrame)
  5472. requester.webkitRequestAnimationFrame(func);
  5473. else if (requester.mozRequestAnimationFrame)
  5474. requester.mozRequestAnimationFrame(func);
  5475. else if (requester.oRequestAnimationFrame)
  5476. requester.oRequestAnimationFrame(func);
  5477. else {
  5478. window.setTimeout(func, 16);
  5479. }
  5480. };
  5481. Tools.RequestFullscreen = function (element) {
  5482. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5483. if (!requestFunction)
  5484. return;
  5485. requestFunction.call(element);
  5486. };
  5487. Tools.ExitFullscreen = function () {
  5488. if (document.exitFullscreen) {
  5489. document.exitFullscreen();
  5490. }
  5491. else if (document.mozCancelFullScreen) {
  5492. document.mozCancelFullScreen();
  5493. }
  5494. else if (document.webkitCancelFullScreen) {
  5495. document.webkitCancelFullScreen();
  5496. }
  5497. else if (document.msCancelFullScreen) {
  5498. document.msCancelFullScreen();
  5499. }
  5500. };
  5501. Tools.SetCorsBehavior = function (url, img) {
  5502. if (Tools.CorsBehavior) {
  5503. switch (typeof (Tools.CorsBehavior)) {
  5504. case "function":
  5505. var result = Tools.CorsBehavior(url);
  5506. if (result) {
  5507. img.crossOrigin = result;
  5508. }
  5509. break;
  5510. case "string":
  5511. default:
  5512. img.crossOrigin = Tools.CorsBehavior;
  5513. break;
  5514. }
  5515. }
  5516. };
  5517. // External files
  5518. Tools.CleanUrl = function (url) {
  5519. url = url.replace(/#/mg, "%23");
  5520. return url;
  5521. };
  5522. Tools.LoadImage = function (url, onload, onerror, database) {
  5523. if (url instanceof ArrayBuffer) {
  5524. url = Tools.EncodeArrayBufferTobase64(url);
  5525. }
  5526. url = Tools.CleanUrl(url);
  5527. var img = new Image();
  5528. if (url.substr(0, 5) !== "data:") {
  5529. Tools.SetCorsBehavior(url, img);
  5530. }
  5531. img.onload = function () {
  5532. onload(img);
  5533. };
  5534. img.onerror = function (err) {
  5535. Tools.Error("Error while trying to load image: " + url);
  5536. if (Tools.UseFallbackTexture) {
  5537. img.src = Tools.fallbackTexture;
  5538. onload(img);
  5539. }
  5540. else {
  5541. onerror();
  5542. }
  5543. };
  5544. var noIndexedDB = function () {
  5545. img.src = url;
  5546. };
  5547. var loadFromIndexedDB = function () {
  5548. database.loadImageFromDB(url, img);
  5549. };
  5550. //ANY database to do!
  5551. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5552. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5553. }
  5554. else {
  5555. if (url.indexOf("file:") !== 0) {
  5556. noIndexedDB();
  5557. }
  5558. else {
  5559. var textureName = url.substring(5).toLowerCase();
  5560. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5561. try {
  5562. var blobURL;
  5563. try {
  5564. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5565. }
  5566. catch (ex) {
  5567. // Chrome doesn't support oneTimeOnly parameter
  5568. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5569. }
  5570. img.src = blobURL;
  5571. }
  5572. catch (e) {
  5573. img.src = null;
  5574. }
  5575. }
  5576. else {
  5577. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5578. img.src = Tools.fallbackTexture;
  5579. }
  5580. }
  5581. }
  5582. return img;
  5583. };
  5584. //ANY
  5585. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5586. url = Tools.CleanUrl(url);
  5587. var noIndexedDB = function () {
  5588. var request = new XMLHttpRequest();
  5589. var loadUrl = Tools.BaseUrl + url;
  5590. request.open('GET', loadUrl, true);
  5591. if (useArrayBuffer) {
  5592. request.responseType = "arraybuffer";
  5593. }
  5594. request.onprogress = progressCallBack;
  5595. request.onreadystatechange = function () {
  5596. // In case of undefined state in some browsers.
  5597. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5598. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5599. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5600. callback(!useArrayBuffer ? request.responseText : request.response);
  5601. }
  5602. else {
  5603. if (onError) {
  5604. onError(request);
  5605. }
  5606. else {
  5607. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5608. }
  5609. }
  5610. }
  5611. };
  5612. request.send(null);
  5613. };
  5614. var loadFromIndexedDB = function () {
  5615. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5616. };
  5617. if (url.indexOf("file:") !== -1) {
  5618. var fileName = url.substring(5).toLowerCase();
  5619. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5620. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5621. }
  5622. else {
  5623. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5624. }
  5625. }
  5626. else {
  5627. // Caching all files
  5628. if (database && database.enableSceneOffline) {
  5629. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5630. }
  5631. else {
  5632. noIndexedDB();
  5633. }
  5634. }
  5635. };
  5636. /**
  5637. * Load a script (identified by an url). When the url returns, the
  5638. * content of this file is added into a new script element, attached to the DOM (body element)
  5639. */
  5640. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5641. var head = document.getElementsByTagName('head')[0];
  5642. var script = document.createElement('script');
  5643. script.type = 'text/javascript';
  5644. script.src = scriptUrl;
  5645. var self = this;
  5646. script.onload = function () {
  5647. if (onSuccess) {
  5648. onSuccess();
  5649. }
  5650. };
  5651. script.onerror = function () {
  5652. if (onError) {
  5653. onError();
  5654. }
  5655. };
  5656. head.appendChild(script);
  5657. };
  5658. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5659. var reader = new FileReader();
  5660. reader.onload = function (e) {
  5661. //target doesn't have result from ts 1.3
  5662. callback(e.target['result']);
  5663. };
  5664. reader.onprogress = progressCallback;
  5665. reader.readAsDataURL(fileToLoad);
  5666. };
  5667. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5668. var reader = new FileReader();
  5669. reader.onerror = function (e) {
  5670. Tools.Log("Error while reading file: " + fileToLoad.name);
  5671. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5672. };
  5673. reader.onload = function (e) {
  5674. //target doesn't have result from ts 1.3
  5675. callback(e.target['result']);
  5676. };
  5677. reader.onprogress = progressCallBack;
  5678. if (!useArrayBuffer) {
  5679. // Asynchronous read
  5680. reader.readAsText(fileToLoad);
  5681. }
  5682. else {
  5683. reader.readAsArrayBuffer(fileToLoad);
  5684. }
  5685. };
  5686. //returns a downloadable url to a file content.
  5687. Tools.FileAsURL = function (content) {
  5688. var fileBlob = new Blob([content]);
  5689. var url = window.URL || window.webkitURL;
  5690. var link = url.createObjectURL(fileBlob);
  5691. return link;
  5692. };
  5693. // Misc.
  5694. Tools.Format = function (value, decimals) {
  5695. if (decimals === void 0) { decimals = 2; }
  5696. return value.toFixed(decimals);
  5697. };
  5698. Tools.CheckExtends = function (v, min, max) {
  5699. if (v.x < min.x)
  5700. min.x = v.x;
  5701. if (v.y < min.y)
  5702. min.y = v.y;
  5703. if (v.z < min.z)
  5704. min.z = v.z;
  5705. if (v.x > max.x)
  5706. max.x = v.x;
  5707. if (v.y > max.y)
  5708. max.y = v.y;
  5709. if (v.z > max.z)
  5710. max.z = v.z;
  5711. };
  5712. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5713. for (var prop in source) {
  5714. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5715. continue;
  5716. }
  5717. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5718. continue;
  5719. }
  5720. var sourceValue = source[prop];
  5721. var typeOfSourceValue = typeof sourceValue;
  5722. if (typeOfSourceValue === "function") {
  5723. continue;
  5724. }
  5725. if (typeOfSourceValue === "object") {
  5726. if (sourceValue instanceof Array) {
  5727. destination[prop] = [];
  5728. if (sourceValue.length > 0) {
  5729. if (typeof sourceValue[0] == "object") {
  5730. for (var index = 0; index < sourceValue.length; index++) {
  5731. var clonedValue = cloneValue(sourceValue[index], destination);
  5732. if (destination[prop].indexOf(clonedValue) === -1) {
  5733. destination[prop].push(clonedValue);
  5734. }
  5735. }
  5736. }
  5737. else {
  5738. destination[prop] = sourceValue.slice(0);
  5739. }
  5740. }
  5741. }
  5742. else {
  5743. destination[prop] = cloneValue(sourceValue, destination);
  5744. }
  5745. }
  5746. else {
  5747. destination[prop] = sourceValue;
  5748. }
  5749. }
  5750. };
  5751. Tools.IsEmpty = function (obj) {
  5752. for (var i in obj) {
  5753. return false;
  5754. }
  5755. return true;
  5756. };
  5757. Tools.RegisterTopRootEvents = function (events) {
  5758. for (var index = 0; index < events.length; index++) {
  5759. var event = events[index];
  5760. window.addEventListener(event.name, event.handler, false);
  5761. try {
  5762. if (window.parent) {
  5763. window.parent.addEventListener(event.name, event.handler, false);
  5764. }
  5765. }
  5766. catch (e) {
  5767. // Silently fails...
  5768. }
  5769. }
  5770. };
  5771. Tools.UnregisterTopRootEvents = function (events) {
  5772. for (var index = 0; index < events.length; index++) {
  5773. var event = events[index];
  5774. window.removeEventListener(event.name, event.handler);
  5775. try {
  5776. if (window.parent) {
  5777. window.parent.removeEventListener(event.name, event.handler);
  5778. }
  5779. }
  5780. catch (e) {
  5781. // Silently fails...
  5782. }
  5783. }
  5784. };
  5785. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5786. if (mimeType === void 0) { mimeType = "image/png"; }
  5787. // Read the contents of the framebuffer
  5788. var numberOfChannelsByLine = width * 4;
  5789. var halfHeight = height / 2;
  5790. //Reading datas from WebGL
  5791. var data = engine.readPixels(0, 0, width, height);
  5792. //To flip image on Y axis.
  5793. for (var i = 0; i < halfHeight; i++) {
  5794. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5795. var currentCell = j + i * numberOfChannelsByLine;
  5796. var targetLine = height - i - 1;
  5797. var targetCell = j + targetLine * numberOfChannelsByLine;
  5798. var temp = data[currentCell];
  5799. data[currentCell] = data[targetCell];
  5800. data[targetCell] = temp;
  5801. }
  5802. }
  5803. // Create a 2D canvas to store the result
  5804. if (!screenshotCanvas) {
  5805. screenshotCanvas = document.createElement('canvas');
  5806. }
  5807. screenshotCanvas.width = width;
  5808. screenshotCanvas.height = height;
  5809. var context = screenshotCanvas.getContext('2d');
  5810. // Copy the pixels to a 2D canvas
  5811. var imageData = context.createImageData(width, height);
  5812. var castData = (imageData.data);
  5813. castData.set(data);
  5814. context.putImageData(imageData, 0, 0);
  5815. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5816. };
  5817. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5818. if (mimeType === void 0) { mimeType = "image/png"; }
  5819. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5820. if (successCallback) {
  5821. successCallback(base64Image);
  5822. }
  5823. else {
  5824. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5825. if (("download" in document.createElement("a"))) {
  5826. var a = window.document.createElement("a");
  5827. a.href = base64Image;
  5828. var date = new Date();
  5829. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5830. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5831. window.document.body.appendChild(a);
  5832. a.addEventListener("click", function () {
  5833. a.parentElement.removeChild(a);
  5834. });
  5835. a.click();
  5836. //Or opening a new tab with the image if it is not possible to automatically start download.
  5837. }
  5838. else {
  5839. var newWindow = window.open("");
  5840. var img = newWindow.document.createElement("img");
  5841. img.src = base64Image;
  5842. newWindow.document.body.appendChild(img);
  5843. }
  5844. }
  5845. };
  5846. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5847. if (mimeType === void 0) { mimeType = "image/png"; }
  5848. var width;
  5849. var height;
  5850. // If a precision value is specified
  5851. if (size.precision) {
  5852. width = Math.round(engine.getRenderWidth() * size.precision);
  5853. height = Math.round(width / engine.getAspectRatio(camera));
  5854. }
  5855. else if (size.width && size.height) {
  5856. width = size.width;
  5857. height = size.height;
  5858. }
  5859. else if (size.width && !size.height) {
  5860. width = size.width;
  5861. height = Math.round(width / engine.getAspectRatio(camera));
  5862. }
  5863. else if (size.height && !size.width) {
  5864. height = size.height;
  5865. width = Math.round(height * engine.getAspectRatio(camera));
  5866. }
  5867. else if (!isNaN(size)) {
  5868. height = size;
  5869. width = size;
  5870. }
  5871. else {
  5872. Tools.Error("Invalid 'size' parameter !");
  5873. return;
  5874. }
  5875. if (!screenshotCanvas) {
  5876. screenshotCanvas = document.createElement('canvas');
  5877. }
  5878. screenshotCanvas.width = width;
  5879. screenshotCanvas.height = height;
  5880. var renderContext = screenshotCanvas.getContext("2d");
  5881. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5882. var newWidth = width;
  5883. var newHeight = newWidth / ratio;
  5884. if (newHeight > height) {
  5885. newHeight = height;
  5886. newWidth = newHeight * ratio;
  5887. }
  5888. var offsetX = Math.max(0, width - newWidth) / 2;
  5889. var offsetY = Math.max(0, height - newHeight) / 2;
  5890. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5891. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5892. };
  5893. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5894. if (mimeType === void 0) { mimeType = "image/png"; }
  5895. if (samples === void 0) { samples = 1; }
  5896. var width;
  5897. var height;
  5898. //If a precision value is specified
  5899. if (size.precision) {
  5900. width = Math.round(engine.getRenderWidth() * size.precision);
  5901. height = Math.round(width / engine.getAspectRatio(camera));
  5902. size = { width: width, height: height };
  5903. }
  5904. else if (size.width && size.height) {
  5905. width = size.width;
  5906. height = size.height;
  5907. }
  5908. else if (size.width && !size.height) {
  5909. width = size.width;
  5910. height = Math.round(width / engine.getAspectRatio(camera));
  5911. size = { width: width, height: height };
  5912. }
  5913. else if (size.height && !size.width) {
  5914. height = size.height;
  5915. width = Math.round(height * engine.getAspectRatio(camera));
  5916. size = { width: width, height: height };
  5917. }
  5918. else if (!isNaN(size)) {
  5919. height = size;
  5920. width = size;
  5921. }
  5922. else {
  5923. Tools.Error("Invalid 'size' parameter !");
  5924. return;
  5925. }
  5926. var scene = camera.getScene();
  5927. var previousCamera = null;
  5928. if (scene.activeCamera !== camera) {
  5929. previousCamera = scene.activeCamera;
  5930. scene.activeCamera = camera;
  5931. }
  5932. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5933. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5934. texture.renderList = scene.meshes;
  5935. texture.samples = samples;
  5936. texture.onAfterRenderObservable.add(function () {
  5937. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5938. });
  5939. scene.incrementRenderId();
  5940. scene.resetCachedMaterial();
  5941. texture.render(true);
  5942. texture.dispose();
  5943. if (previousCamera) {
  5944. scene.activeCamera = previousCamera;
  5945. }
  5946. camera.getProjectionMatrix(true); // Force cache refresh;
  5947. };
  5948. // XHR response validator for local file scenario
  5949. Tools.ValidateXHRData = function (xhr, dataType) {
  5950. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5951. if (dataType === void 0) { dataType = 7; }
  5952. try {
  5953. if (dataType & 1) {
  5954. if (xhr.responseText && xhr.responseText.length > 0) {
  5955. return true;
  5956. }
  5957. else if (dataType === 1) {
  5958. return false;
  5959. }
  5960. }
  5961. if (dataType & 2) {
  5962. // Check header width and height since there is no "TGA" magic number
  5963. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5964. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5965. return true;
  5966. }
  5967. else if (dataType === 2) {
  5968. return false;
  5969. }
  5970. }
  5971. if (dataType & 4) {
  5972. // Check for the "DDS" magic number
  5973. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5974. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5975. return true;
  5976. }
  5977. else {
  5978. return false;
  5979. }
  5980. }
  5981. }
  5982. catch (e) {
  5983. // Global protection
  5984. }
  5985. return false;
  5986. };
  5987. /**
  5988. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5989. * Be aware Math.random() could cause collisions, but:
  5990. * "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"
  5991. */
  5992. Tools.RandomId = function () {
  5993. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5994. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5995. return v.toString(16);
  5996. });
  5997. };
  5998. Object.defineProperty(Tools, "NoneLogLevel", {
  5999. get: function () {
  6000. return Tools._NoneLogLevel;
  6001. },
  6002. enumerable: true,
  6003. configurable: true
  6004. });
  6005. Object.defineProperty(Tools, "MessageLogLevel", {
  6006. get: function () {
  6007. return Tools._MessageLogLevel;
  6008. },
  6009. enumerable: true,
  6010. configurable: true
  6011. });
  6012. Object.defineProperty(Tools, "WarningLogLevel", {
  6013. get: function () {
  6014. return Tools._WarningLogLevel;
  6015. },
  6016. enumerable: true,
  6017. configurable: true
  6018. });
  6019. Object.defineProperty(Tools, "ErrorLogLevel", {
  6020. get: function () {
  6021. return Tools._ErrorLogLevel;
  6022. },
  6023. enumerable: true,
  6024. configurable: true
  6025. });
  6026. Object.defineProperty(Tools, "AllLogLevel", {
  6027. get: function () {
  6028. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6029. },
  6030. enumerable: true,
  6031. configurable: true
  6032. });
  6033. Tools._AddLogEntry = function (entry) {
  6034. Tools._LogCache = entry + Tools._LogCache;
  6035. if (Tools.OnNewCacheEntry) {
  6036. Tools.OnNewCacheEntry(entry);
  6037. }
  6038. };
  6039. Tools._FormatMessage = function (message) {
  6040. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6041. var date = new Date();
  6042. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6043. };
  6044. Tools._LogDisabled = function (message) {
  6045. // nothing to do
  6046. };
  6047. Tools._LogEnabled = function (message) {
  6048. var formattedMessage = Tools._FormatMessage(message);
  6049. console.log("BJS - " + formattedMessage);
  6050. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6051. Tools._AddLogEntry(entry);
  6052. };
  6053. Tools._WarnDisabled = function (message) {
  6054. // nothing to do
  6055. };
  6056. Tools._WarnEnabled = function (message) {
  6057. var formattedMessage = Tools._FormatMessage(message);
  6058. console.warn("BJS - " + formattedMessage);
  6059. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6060. Tools._AddLogEntry(entry);
  6061. };
  6062. Tools._ErrorDisabled = function (message) {
  6063. // nothing to do
  6064. };
  6065. Tools._ErrorEnabled = function (message) {
  6066. Tools.errorsCount++;
  6067. var formattedMessage = Tools._FormatMessage(message);
  6068. console.error("BJS - " + formattedMessage);
  6069. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6070. Tools._AddLogEntry(entry);
  6071. };
  6072. Object.defineProperty(Tools, "LogCache", {
  6073. get: function () {
  6074. return Tools._LogCache;
  6075. },
  6076. enumerable: true,
  6077. configurable: true
  6078. });
  6079. Tools.ClearLogCache = function () {
  6080. Tools._LogCache = "";
  6081. Tools.errorsCount = 0;
  6082. };
  6083. Object.defineProperty(Tools, "LogLevels", {
  6084. set: function (level) {
  6085. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6086. Tools.Log = Tools._LogEnabled;
  6087. }
  6088. else {
  6089. Tools.Log = Tools._LogDisabled;
  6090. }
  6091. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6092. Tools.Warn = Tools._WarnEnabled;
  6093. }
  6094. else {
  6095. Tools.Warn = Tools._WarnDisabled;
  6096. }
  6097. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6098. Tools.Error = Tools._ErrorEnabled;
  6099. }
  6100. else {
  6101. Tools.Error = Tools._ErrorDisabled;
  6102. }
  6103. },
  6104. enumerable: true,
  6105. configurable: true
  6106. });
  6107. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6108. get: function () {
  6109. return Tools._PerformanceNoneLogLevel;
  6110. },
  6111. enumerable: true,
  6112. configurable: true
  6113. });
  6114. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6115. get: function () {
  6116. return Tools._PerformanceUserMarkLogLevel;
  6117. },
  6118. enumerable: true,
  6119. configurable: true
  6120. });
  6121. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6122. get: function () {
  6123. return Tools._PerformanceConsoleLogLevel;
  6124. },
  6125. enumerable: true,
  6126. configurable: true
  6127. });
  6128. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6129. set: function (level) {
  6130. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6131. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6132. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6133. return;
  6134. }
  6135. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6136. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6137. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6138. return;
  6139. }
  6140. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6141. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6142. },
  6143. enumerable: true,
  6144. configurable: true
  6145. });
  6146. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6147. };
  6148. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6149. };
  6150. Tools._StartUserMark = function (counterName, condition) {
  6151. if (condition === void 0) { condition = true; }
  6152. if (!condition || !Tools._performance.mark) {
  6153. return;
  6154. }
  6155. Tools._performance.mark(counterName + "-Begin");
  6156. };
  6157. Tools._EndUserMark = function (counterName, condition) {
  6158. if (condition === void 0) { condition = true; }
  6159. if (!condition || !Tools._performance.mark) {
  6160. return;
  6161. }
  6162. Tools._performance.mark(counterName + "-End");
  6163. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6164. };
  6165. Tools._StartPerformanceConsole = function (counterName, condition) {
  6166. if (condition === void 0) { condition = true; }
  6167. if (!condition) {
  6168. return;
  6169. }
  6170. Tools._StartUserMark(counterName, condition);
  6171. if (console.time) {
  6172. console.time(counterName);
  6173. }
  6174. };
  6175. Tools._EndPerformanceConsole = function (counterName, condition) {
  6176. if (condition === void 0) { condition = true; }
  6177. if (!condition) {
  6178. return;
  6179. }
  6180. Tools._EndUserMark(counterName, condition);
  6181. if (console.time) {
  6182. console.timeEnd(counterName);
  6183. }
  6184. };
  6185. Object.defineProperty(Tools, "Now", {
  6186. get: function () {
  6187. if (window.performance && window.performance.now) {
  6188. return window.performance.now();
  6189. }
  6190. return new Date().getTime();
  6191. },
  6192. enumerable: true,
  6193. configurable: true
  6194. });
  6195. /**
  6196. * This method will return the name of the class used to create the instance of the given object.
  6197. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6198. * @param object the object to get the class name from
  6199. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6200. */
  6201. Tools.getClassName = function (object, isType) {
  6202. if (isType === void 0) { isType = false; }
  6203. var name = null;
  6204. if (!isType && object.getClassName) {
  6205. name = object.getClassName();
  6206. }
  6207. else {
  6208. if (object instanceof Object) {
  6209. var classObj = isType ? object : Object.getPrototypeOf(object);
  6210. name = classObj.constructor["__bjsclassName__"];
  6211. }
  6212. if (!name) {
  6213. name = typeof object;
  6214. }
  6215. }
  6216. return name;
  6217. };
  6218. Tools.first = function (array, predicate) {
  6219. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6220. var el = array_1[_i];
  6221. if (predicate(el)) {
  6222. return el;
  6223. }
  6224. }
  6225. };
  6226. /**
  6227. * This method will return the name of the full name of the class, including its owning module (if any).
  6228. * 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).
  6229. * @param object the object to get the class name from
  6230. * @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.
  6231. */
  6232. Tools.getFullClassName = function (object, isType) {
  6233. if (isType === void 0) { isType = false; }
  6234. var className = null;
  6235. var moduleName = null;
  6236. if (!isType && object.getClassName) {
  6237. className = object.getClassName();
  6238. }
  6239. else {
  6240. if (object instanceof Object) {
  6241. var classObj = isType ? object : Object.getPrototypeOf(object);
  6242. className = classObj.constructor["__bjsclassName__"];
  6243. moduleName = classObj.constructor["__bjsmoduleName__"];
  6244. }
  6245. if (!className) {
  6246. className = typeof object;
  6247. }
  6248. }
  6249. if (!className) {
  6250. return null;
  6251. }
  6252. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6253. };
  6254. /**
  6255. * 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.
  6256. * @param array
  6257. */
  6258. Tools.arrayOrStringFeeder = function (array) {
  6259. return function (index) {
  6260. if (index >= array.length) {
  6261. return null;
  6262. }
  6263. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6264. if (val && val.getHashCode) {
  6265. val = val.getHashCode();
  6266. }
  6267. if (typeof val === "string") {
  6268. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6269. }
  6270. return val;
  6271. };
  6272. };
  6273. /**
  6274. * Compute the hashCode of a stream of number
  6275. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6276. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6277. * @return the hash code computed
  6278. */
  6279. Tools.hashCodeFromStream = function (feeder) {
  6280. // Based from here: http://stackoverflow.com/a/7616484/802124
  6281. var hash = 0;
  6282. var index = 0;
  6283. var chr = feeder(index++);
  6284. while (chr != null) {
  6285. hash = ((hash << 5) - hash) + chr;
  6286. hash |= 0; // Convert to 32bit integer
  6287. chr = feeder(index++);
  6288. }
  6289. return hash;
  6290. };
  6291. return Tools;
  6292. }());
  6293. Tools.BaseUrl = "";
  6294. Tools.CorsBehavior = "anonymous";
  6295. Tools.UseFallbackTexture = true;
  6296. // Used in case of a texture loading problem
  6297. 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";
  6298. // Logs
  6299. Tools._NoneLogLevel = 0;
  6300. Tools._MessageLogLevel = 1;
  6301. Tools._WarningLogLevel = 2;
  6302. Tools._ErrorLogLevel = 4;
  6303. Tools._LogCache = "";
  6304. Tools.errorsCount = 0;
  6305. Tools.Log = Tools._LogEnabled;
  6306. Tools.Warn = Tools._WarnEnabled;
  6307. Tools.Error = Tools._ErrorEnabled;
  6308. // Performances
  6309. Tools._PerformanceNoneLogLevel = 0;
  6310. Tools._PerformanceUserMarkLogLevel = 1;
  6311. Tools._PerformanceConsoleLogLevel = 2;
  6312. Tools._performance = window.performance;
  6313. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6314. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6315. BABYLON.Tools = Tools;
  6316. /**
  6317. * This class is used to track a performance counter which is number based.
  6318. * The user has access to many properties which give statistics of different nature
  6319. *
  6320. * The implementer can track two kinds of Performance Counter: time and count
  6321. * 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.
  6322. * 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.
  6323. */
  6324. var PerfCounter = (function () {
  6325. function PerfCounter() {
  6326. this._startMonitoringTime = 0;
  6327. this._min = 0;
  6328. this._max = 0;
  6329. this._average = 0;
  6330. this._lastSecAverage = 0;
  6331. this._current = 0;
  6332. this._totalValueCount = 0;
  6333. this._totalAccumulated = 0;
  6334. this._lastSecAccumulated = 0;
  6335. this._lastSecTime = 0;
  6336. this._lastSecValueCount = 0;
  6337. }
  6338. Object.defineProperty(PerfCounter.prototype, "min", {
  6339. /**
  6340. * Returns the smallest value ever
  6341. */
  6342. get: function () {
  6343. return this._min;
  6344. },
  6345. enumerable: true,
  6346. configurable: true
  6347. });
  6348. Object.defineProperty(PerfCounter.prototype, "max", {
  6349. /**
  6350. * Returns the biggest value ever
  6351. */
  6352. get: function () {
  6353. return this._max;
  6354. },
  6355. enumerable: true,
  6356. configurable: true
  6357. });
  6358. Object.defineProperty(PerfCounter.prototype, "average", {
  6359. /**
  6360. * Returns the average value since the performance counter is running
  6361. */
  6362. get: function () {
  6363. return this._average;
  6364. },
  6365. enumerable: true,
  6366. configurable: true
  6367. });
  6368. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6369. /**
  6370. * Returns the average value of the last second the counter was monitored
  6371. */
  6372. get: function () {
  6373. return this._lastSecAverage;
  6374. },
  6375. enumerable: true,
  6376. configurable: true
  6377. });
  6378. Object.defineProperty(PerfCounter.prototype, "current", {
  6379. /**
  6380. * Returns the current value
  6381. */
  6382. get: function () {
  6383. return this._current;
  6384. },
  6385. enumerable: true,
  6386. configurable: true
  6387. });
  6388. Object.defineProperty(PerfCounter.prototype, "total", {
  6389. get: function () {
  6390. return this._totalAccumulated;
  6391. },
  6392. enumerable: true,
  6393. configurable: true
  6394. });
  6395. /**
  6396. * Call this method to start monitoring a new frame.
  6397. * 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.
  6398. */
  6399. PerfCounter.prototype.fetchNewFrame = function () {
  6400. this._totalValueCount++;
  6401. this._current = 0;
  6402. this._lastSecValueCount++;
  6403. };
  6404. /**
  6405. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6406. * @param newCount the count value to add to the monitored count
  6407. * @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.
  6408. */
  6409. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6410. if (!PerfCounter.Enabled) {
  6411. return;
  6412. }
  6413. this._current += newCount;
  6414. if (fetchResult) {
  6415. this._fetchResult();
  6416. }
  6417. };
  6418. /**
  6419. * Start monitoring this performance counter
  6420. */
  6421. PerfCounter.prototype.beginMonitoring = function () {
  6422. if (!PerfCounter.Enabled) {
  6423. return;
  6424. }
  6425. this._startMonitoringTime = Tools.Now;
  6426. };
  6427. /**
  6428. * Compute the time lapsed since the previous beginMonitoring() call.
  6429. * @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
  6430. */
  6431. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6432. if (newFrame === void 0) { newFrame = true; }
  6433. if (!PerfCounter.Enabled) {
  6434. return;
  6435. }
  6436. if (newFrame) {
  6437. this.fetchNewFrame();
  6438. }
  6439. var currentTime = Tools.Now;
  6440. this._current = currentTime - this._startMonitoringTime;
  6441. if (newFrame) {
  6442. this._fetchResult();
  6443. }
  6444. };
  6445. PerfCounter.prototype._fetchResult = function () {
  6446. this._totalAccumulated += this._current;
  6447. this._lastSecAccumulated += this._current;
  6448. // Min/Max update
  6449. this._min = Math.min(this._min, this._current);
  6450. this._max = Math.max(this._max, this._current);
  6451. this._average = this._totalAccumulated / this._totalValueCount;
  6452. // Reset last sec?
  6453. var now = Tools.Now;
  6454. if ((now - this._lastSecTime) > 1000) {
  6455. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6456. this._lastSecTime = now;
  6457. this._lastSecAccumulated = 0;
  6458. this._lastSecValueCount = 0;
  6459. }
  6460. };
  6461. return PerfCounter;
  6462. }());
  6463. PerfCounter.Enabled = true;
  6464. BABYLON.PerfCounter = PerfCounter;
  6465. /**
  6466. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6467. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6468. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6469. * @param name The name of the class, case should be preserved
  6470. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6471. */
  6472. function className(name, module) {
  6473. return function (target) {
  6474. target["__bjsclassName__"] = name;
  6475. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6476. };
  6477. }
  6478. BABYLON.className = className;
  6479. /**
  6480. * An implementation of a loop for asynchronous functions.
  6481. */
  6482. var AsyncLoop = (function () {
  6483. /**
  6484. * Constroctor.
  6485. * @param iterations the number of iterations.
  6486. * @param _fn the function to run each iteration
  6487. * @param _successCallback the callback that will be called upon succesful execution
  6488. * @param offset starting offset.
  6489. */
  6490. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6491. if (offset === void 0) { offset = 0; }
  6492. this.iterations = iterations;
  6493. this._fn = _fn;
  6494. this._successCallback = _successCallback;
  6495. this.index = offset - 1;
  6496. this._done = false;
  6497. }
  6498. /**
  6499. * Execute the next iteration. Must be called after the last iteration was finished.
  6500. */
  6501. AsyncLoop.prototype.executeNext = function () {
  6502. if (!this._done) {
  6503. if (this.index + 1 < this.iterations) {
  6504. ++this.index;
  6505. this._fn(this);
  6506. }
  6507. else {
  6508. this.breakLoop();
  6509. }
  6510. }
  6511. };
  6512. /**
  6513. * Break the loop and run the success callback.
  6514. */
  6515. AsyncLoop.prototype.breakLoop = function () {
  6516. this._done = true;
  6517. this._successCallback();
  6518. };
  6519. /**
  6520. * Helper function
  6521. */
  6522. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6523. if (offset === void 0) { offset = 0; }
  6524. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6525. loop.executeNext();
  6526. return loop;
  6527. };
  6528. /**
  6529. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6530. * @param iterations total number of iterations
  6531. * @param syncedIterations number of synchronous iterations in each async iteration.
  6532. * @param fn the function to call each iteration.
  6533. * @param callback a success call back that will be called when iterating stops.
  6534. * @param breakFunction a break condition (optional)
  6535. * @param timeout timeout settings for the setTimeout function. default - 0.
  6536. * @constructor
  6537. */
  6538. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6539. if (timeout === void 0) { timeout = 0; }
  6540. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6541. if (breakFunction && breakFunction())
  6542. loop.breakLoop();
  6543. else {
  6544. setTimeout(function () {
  6545. for (var i = 0; i < syncedIterations; ++i) {
  6546. var iteration = (loop.index * syncedIterations) + i;
  6547. if (iteration >= iterations)
  6548. break;
  6549. fn(iteration);
  6550. if (breakFunction && breakFunction()) {
  6551. loop.breakLoop();
  6552. break;
  6553. }
  6554. }
  6555. loop.executeNext();
  6556. }, timeout);
  6557. }
  6558. }, callback);
  6559. };
  6560. return AsyncLoop;
  6561. }());
  6562. BABYLON.AsyncLoop = AsyncLoop;
  6563. })(BABYLON || (BABYLON = {}));
  6564. //# sourceMappingURL=babylon.tools.js.map
  6565. var BABYLON;
  6566. (function (BABYLON) {
  6567. var Internals;
  6568. (function (Internals) {
  6569. var _AlphaState = (function () {
  6570. /**
  6571. * Initializes the state.
  6572. */
  6573. function _AlphaState() {
  6574. this._isAlphaBlendDirty = false;
  6575. this._isBlendFunctionParametersDirty = false;
  6576. this._isBlendEquationParametersDirty = false;
  6577. this._isBlendConstantsDirty = false;
  6578. this._alphaBlend = false;
  6579. this._blendFunctionParameters = new Array(4);
  6580. this._blendEquationParameters = new Array(2);
  6581. this._blendConstants = new Array(4);
  6582. this.reset();
  6583. }
  6584. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6585. get: function () {
  6586. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6587. },
  6588. enumerable: true,
  6589. configurable: true
  6590. });
  6591. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6592. get: function () {
  6593. return this._alphaBlend;
  6594. },
  6595. set: function (value) {
  6596. if (this._alphaBlend === value) {
  6597. return;
  6598. }
  6599. this._alphaBlend = value;
  6600. this._isAlphaBlendDirty = true;
  6601. },
  6602. enumerable: true,
  6603. configurable: true
  6604. });
  6605. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6606. if (this._blendConstants[0] === r &&
  6607. this._blendConstants[1] === g &&
  6608. this._blendConstants[2] === b &&
  6609. this._blendConstants[3] === a) {
  6610. return;
  6611. }
  6612. this._blendConstants[0] = r;
  6613. this._blendConstants[1] = g;
  6614. this._blendConstants[2] = b;
  6615. this._blendConstants[3] = a;
  6616. this._isBlendConstantsDirty = true;
  6617. };
  6618. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6619. if (this._blendFunctionParameters[0] === value0 &&
  6620. this._blendFunctionParameters[1] === value1 &&
  6621. this._blendFunctionParameters[2] === value2 &&
  6622. this._blendFunctionParameters[3] === value3) {
  6623. return;
  6624. }
  6625. this._blendFunctionParameters[0] = value0;
  6626. this._blendFunctionParameters[1] = value1;
  6627. this._blendFunctionParameters[2] = value2;
  6628. this._blendFunctionParameters[3] = value3;
  6629. this._isBlendFunctionParametersDirty = true;
  6630. };
  6631. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6632. if (this._blendEquationParameters[0] === rgb &&
  6633. this._blendEquationParameters[1] === alpha) {
  6634. return;
  6635. }
  6636. this._blendEquationParameters[0] = rgb;
  6637. this._blendEquationParameters[1] = alpha;
  6638. this._isBlendEquationParametersDirty = true;
  6639. };
  6640. _AlphaState.prototype.reset = function () {
  6641. this._alphaBlend = false;
  6642. this._blendFunctionParameters[0] = null;
  6643. this._blendFunctionParameters[1] = null;
  6644. this._blendFunctionParameters[2] = null;
  6645. this._blendFunctionParameters[3] = null;
  6646. this._blendEquationParameters[0] = null;
  6647. this._blendEquationParameters[1] = null;
  6648. this._blendConstants[0] = null;
  6649. this._blendConstants[1] = null;
  6650. this._blendConstants[2] = null;
  6651. this._blendConstants[3] = null;
  6652. this._isAlphaBlendDirty = true;
  6653. this._isBlendFunctionParametersDirty = false;
  6654. this._isBlendEquationParametersDirty = false;
  6655. this._isBlendConstantsDirty = false;
  6656. };
  6657. _AlphaState.prototype.apply = function (gl) {
  6658. if (!this.isDirty) {
  6659. return;
  6660. }
  6661. // Alpha blend
  6662. if (this._isAlphaBlendDirty) {
  6663. if (this._alphaBlend) {
  6664. gl.enable(gl.BLEND);
  6665. }
  6666. else {
  6667. gl.disable(gl.BLEND);
  6668. }
  6669. this._isAlphaBlendDirty = false;
  6670. }
  6671. // Alpha function
  6672. if (this._isBlendFunctionParametersDirty) {
  6673. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6674. this._isBlendFunctionParametersDirty = false;
  6675. }
  6676. // Alpha equation
  6677. if (this._isBlendEquationParametersDirty) {
  6678. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6679. this._isBlendEquationParametersDirty = false;
  6680. }
  6681. // Constants
  6682. if (this._isBlendConstantsDirty) {
  6683. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6684. this._isBlendConstantsDirty = false;
  6685. }
  6686. };
  6687. return _AlphaState;
  6688. }());
  6689. Internals._AlphaState = _AlphaState;
  6690. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6691. })(BABYLON || (BABYLON = {}));
  6692. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6693. var BABYLON;
  6694. (function (BABYLON) {
  6695. var Internals;
  6696. (function (Internals) {
  6697. var _DepthCullingState = (function () {
  6698. /**
  6699. * Initializes the state.
  6700. */
  6701. function _DepthCullingState() {
  6702. this._isDepthTestDirty = false;
  6703. this._isDepthMaskDirty = false;
  6704. this._isDepthFuncDirty = false;
  6705. this._isCullFaceDirty = false;
  6706. this._isCullDirty = false;
  6707. this._isZOffsetDirty = false;
  6708. this.reset();
  6709. }
  6710. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6711. get: function () {
  6712. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6718. get: function () {
  6719. return this._zOffset;
  6720. },
  6721. set: function (value) {
  6722. if (this._zOffset === value) {
  6723. return;
  6724. }
  6725. this._zOffset = value;
  6726. this._isZOffsetDirty = true;
  6727. },
  6728. enumerable: true,
  6729. configurable: true
  6730. });
  6731. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6732. get: function () {
  6733. return this._cullFace;
  6734. },
  6735. set: function (value) {
  6736. if (this._cullFace === value) {
  6737. return;
  6738. }
  6739. this._cullFace = value;
  6740. this._isCullFaceDirty = true;
  6741. },
  6742. enumerable: true,
  6743. configurable: true
  6744. });
  6745. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6746. get: function () {
  6747. return this._cull;
  6748. },
  6749. set: function (value) {
  6750. if (this._cull === value) {
  6751. return;
  6752. }
  6753. this._cull = value;
  6754. this._isCullDirty = true;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6760. get: function () {
  6761. return this._depthFunc;
  6762. },
  6763. set: function (value) {
  6764. if (this._depthFunc === value) {
  6765. return;
  6766. }
  6767. this._depthFunc = value;
  6768. this._isDepthFuncDirty = true;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6774. get: function () {
  6775. return this._depthMask;
  6776. },
  6777. set: function (value) {
  6778. if (this._depthMask === value) {
  6779. return;
  6780. }
  6781. this._depthMask = value;
  6782. this._isDepthMaskDirty = true;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6788. get: function () {
  6789. return this._depthTest;
  6790. },
  6791. set: function (value) {
  6792. if (this._depthTest === value) {
  6793. return;
  6794. }
  6795. this._depthTest = value;
  6796. this._isDepthTestDirty = true;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. _DepthCullingState.prototype.reset = function () {
  6802. this._depthMask = true;
  6803. this._depthTest = true;
  6804. this._depthFunc = null;
  6805. this._cullFace = null;
  6806. this._cull = null;
  6807. this._zOffset = 0;
  6808. this._isDepthTestDirty = true;
  6809. this._isDepthMaskDirty = true;
  6810. this._isDepthFuncDirty = false;
  6811. this._isCullFaceDirty = false;
  6812. this._isCullDirty = false;
  6813. this._isZOffsetDirty = false;
  6814. };
  6815. _DepthCullingState.prototype.apply = function (gl) {
  6816. if (!this.isDirty) {
  6817. return;
  6818. }
  6819. // Cull
  6820. if (this._isCullDirty) {
  6821. if (this.cull) {
  6822. gl.enable(gl.CULL_FACE);
  6823. }
  6824. else {
  6825. gl.disable(gl.CULL_FACE);
  6826. }
  6827. this._isCullDirty = false;
  6828. }
  6829. // Cull face
  6830. if (this._isCullFaceDirty) {
  6831. gl.cullFace(this.cullFace);
  6832. this._isCullFaceDirty = false;
  6833. }
  6834. // Depth mask
  6835. if (this._isDepthMaskDirty) {
  6836. gl.depthMask(this.depthMask);
  6837. this._isDepthMaskDirty = false;
  6838. }
  6839. // Depth test
  6840. if (this._isDepthTestDirty) {
  6841. if (this.depthTest) {
  6842. gl.enable(gl.DEPTH_TEST);
  6843. }
  6844. else {
  6845. gl.disable(gl.DEPTH_TEST);
  6846. }
  6847. this._isDepthTestDirty = false;
  6848. }
  6849. // Depth func
  6850. if (this._isDepthFuncDirty) {
  6851. gl.depthFunc(this.depthFunc);
  6852. this._isDepthFuncDirty = false;
  6853. }
  6854. // zOffset
  6855. if (this._isZOffsetDirty) {
  6856. if (this.zOffset) {
  6857. gl.enable(gl.POLYGON_OFFSET_FILL);
  6858. gl.polygonOffset(this.zOffset, 0);
  6859. }
  6860. else {
  6861. gl.disable(gl.POLYGON_OFFSET_FILL);
  6862. }
  6863. this._isZOffsetDirty = false;
  6864. }
  6865. };
  6866. return _DepthCullingState;
  6867. }());
  6868. Internals._DepthCullingState = _DepthCullingState;
  6869. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6870. })(BABYLON || (BABYLON = {}));
  6871. //# sourceMappingURL=babylon.depthCullingState.js.map
  6872. var BABYLON;
  6873. (function (BABYLON) {
  6874. var Internals;
  6875. (function (Internals) {
  6876. var _StencilState = (function () {
  6877. function _StencilState() {
  6878. this._isStencilTestDirty = false;
  6879. this._isStencilMaskDirty = false;
  6880. this._isStencilFuncDirty = false;
  6881. this._isStencilOpDirty = false;
  6882. this.reset();
  6883. }
  6884. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6885. get: function () {
  6886. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6887. },
  6888. enumerable: true,
  6889. configurable: true
  6890. });
  6891. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6892. get: function () {
  6893. return this._stencilFunc;
  6894. },
  6895. set: function (value) {
  6896. if (this._stencilFunc === value) {
  6897. return;
  6898. }
  6899. this._stencilFunc = value;
  6900. this._isStencilFuncDirty = true;
  6901. },
  6902. enumerable: true,
  6903. configurable: true
  6904. });
  6905. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6906. get: function () {
  6907. return this._stencilFuncRef;
  6908. },
  6909. set: function (value) {
  6910. if (this._stencilFuncRef === value) {
  6911. return;
  6912. }
  6913. this._stencilFuncRef = value;
  6914. this._isStencilFuncDirty = true;
  6915. },
  6916. enumerable: true,
  6917. configurable: true
  6918. });
  6919. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6920. get: function () {
  6921. return this._stencilFuncMask;
  6922. },
  6923. set: function (value) {
  6924. if (this._stencilFuncMask === value) {
  6925. return;
  6926. }
  6927. this._stencilFuncMask = value;
  6928. this._isStencilFuncDirty = true;
  6929. },
  6930. enumerable: true,
  6931. configurable: true
  6932. });
  6933. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6934. get: function () {
  6935. return this._stencilOpStencilFail;
  6936. },
  6937. set: function (value) {
  6938. if (this._stencilOpStencilFail === value) {
  6939. return;
  6940. }
  6941. this._stencilOpStencilFail = value;
  6942. this._isStencilOpDirty = true;
  6943. },
  6944. enumerable: true,
  6945. configurable: true
  6946. });
  6947. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6948. get: function () {
  6949. return this._stencilOpDepthFail;
  6950. },
  6951. set: function (value) {
  6952. if (this._stencilOpDepthFail === value) {
  6953. return;
  6954. }
  6955. this._stencilOpDepthFail = value;
  6956. this._isStencilOpDirty = true;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6962. get: function () {
  6963. return this._stencilOpStencilDepthPass;
  6964. },
  6965. set: function (value) {
  6966. if (this._stencilOpStencilDepthPass === value) {
  6967. return;
  6968. }
  6969. this._stencilOpStencilDepthPass = value;
  6970. this._isStencilOpDirty = true;
  6971. },
  6972. enumerable: true,
  6973. configurable: true
  6974. });
  6975. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6976. get: function () {
  6977. return this._stencilMask;
  6978. },
  6979. set: function (value) {
  6980. if (this._stencilMask === value) {
  6981. return;
  6982. }
  6983. this._stencilMask = value;
  6984. this._isStencilMaskDirty = true;
  6985. },
  6986. enumerable: true,
  6987. configurable: true
  6988. });
  6989. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6990. get: function () {
  6991. return this._stencilTest;
  6992. },
  6993. set: function (value) {
  6994. if (this._stencilTest === value) {
  6995. return;
  6996. }
  6997. this._stencilTest = value;
  6998. this._isStencilTestDirty = true;
  6999. },
  7000. enumerable: true,
  7001. configurable: true
  7002. });
  7003. _StencilState.prototype.reset = function () {
  7004. this._stencilTest = false;
  7005. this._stencilMask = 0xFF;
  7006. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7007. this._stencilFuncRef = 1;
  7008. this._stencilFuncMask = 0xFF;
  7009. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7010. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7011. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7012. this._isStencilTestDirty = true;
  7013. this._isStencilMaskDirty = true;
  7014. this._isStencilFuncDirty = true;
  7015. this._isStencilOpDirty = true;
  7016. };
  7017. _StencilState.prototype.apply = function (gl) {
  7018. if (!this.isDirty) {
  7019. return;
  7020. }
  7021. // Stencil test
  7022. if (this._isStencilTestDirty) {
  7023. if (this.stencilTest) {
  7024. gl.enable(gl.STENCIL_TEST);
  7025. }
  7026. else {
  7027. gl.disable(gl.STENCIL_TEST);
  7028. }
  7029. this._isStencilTestDirty = false;
  7030. }
  7031. // Stencil mask
  7032. if (this._isStencilMaskDirty) {
  7033. gl.stencilMask(this.stencilMask);
  7034. this._isStencilMaskDirty = false;
  7035. }
  7036. // Stencil func
  7037. if (this._isStencilFuncDirty) {
  7038. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7039. this._isStencilFuncDirty = false;
  7040. }
  7041. // Stencil op
  7042. if (this._isStencilOpDirty) {
  7043. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7044. this._isStencilOpDirty = false;
  7045. }
  7046. };
  7047. return _StencilState;
  7048. }());
  7049. Internals._StencilState = _StencilState;
  7050. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7051. })(BABYLON || (BABYLON = {}));
  7052. //# sourceMappingURL=babylon.stencilState.js.map
  7053. var BABYLON;
  7054. (function (BABYLON) {
  7055. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7056. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7057. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7058. gl.compileShader(shader);
  7059. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7060. throw new Error(gl.getShaderInfoLog(shader));
  7061. }
  7062. return shader;
  7063. };
  7064. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7065. var magFilter = gl.NEAREST;
  7066. var minFilter = gl.NEAREST;
  7067. switch (samplingMode) {
  7068. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7069. magFilter = gl.LINEAR;
  7070. if (generateMipMaps) {
  7071. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7072. }
  7073. else {
  7074. minFilter = gl.LINEAR;
  7075. }
  7076. break;
  7077. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7078. magFilter = gl.LINEAR;
  7079. if (generateMipMaps) {
  7080. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7081. }
  7082. else {
  7083. minFilter = gl.LINEAR;
  7084. }
  7085. break;
  7086. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7087. magFilter = gl.NEAREST;
  7088. if (generateMipMaps) {
  7089. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7090. }
  7091. else {
  7092. minFilter = gl.NEAREST;
  7093. }
  7094. break;
  7095. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7096. magFilter = gl.NEAREST;
  7097. if (generateMipMaps) {
  7098. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7099. }
  7100. else {
  7101. minFilter = gl.NEAREST;
  7102. }
  7103. break;
  7104. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7105. magFilter = gl.NEAREST;
  7106. if (generateMipMaps) {
  7107. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7108. }
  7109. else {
  7110. minFilter = gl.LINEAR;
  7111. }
  7112. break;
  7113. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7114. magFilter = gl.NEAREST;
  7115. if (generateMipMaps) {
  7116. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7117. }
  7118. else {
  7119. minFilter = gl.LINEAR;
  7120. }
  7121. break;
  7122. case BABYLON.Texture.NEAREST_LINEAR:
  7123. magFilter = gl.NEAREST;
  7124. minFilter = gl.LINEAR;
  7125. break;
  7126. case BABYLON.Texture.NEAREST_NEAREST:
  7127. magFilter = gl.NEAREST;
  7128. minFilter = gl.NEAREST;
  7129. break;
  7130. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7131. magFilter = gl.LINEAR;
  7132. if (generateMipMaps) {
  7133. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7134. }
  7135. else {
  7136. minFilter = gl.NEAREST;
  7137. }
  7138. break;
  7139. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7140. magFilter = gl.LINEAR;
  7141. if (generateMipMaps) {
  7142. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7143. }
  7144. else {
  7145. minFilter = gl.NEAREST;
  7146. }
  7147. break;
  7148. case BABYLON.Texture.LINEAR_LINEAR:
  7149. magFilter = gl.LINEAR;
  7150. minFilter = gl.LINEAR;
  7151. break;
  7152. case BABYLON.Texture.LINEAR_NEAREST:
  7153. magFilter = gl.LINEAR;
  7154. minFilter = gl.NEAREST;
  7155. break;
  7156. }
  7157. return {
  7158. min: minFilter,
  7159. mag: magFilter
  7160. };
  7161. };
  7162. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7163. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7164. var engine = scene.getEngine();
  7165. if (!engine) {
  7166. return;
  7167. }
  7168. var potWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize) : width;
  7169. var potHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize) : height;
  7170. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7171. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7172. texture._baseWidth = width;
  7173. texture._baseHeight = height;
  7174. texture._width = potWidth;
  7175. texture._height = potHeight;
  7176. texture.isReady = true;
  7177. processFunction(potWidth, potHeight);
  7178. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7180. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7181. if (!noMipmap && !isCompressed) {
  7182. gl.generateMipmap(gl.TEXTURE_2D);
  7183. }
  7184. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7185. engine.resetTextureCache();
  7186. scene._removePendingData(texture);
  7187. texture.onLoadedCallbacks.forEach(function (callback) {
  7188. callback();
  7189. });
  7190. texture.onLoadedCallbacks = [];
  7191. };
  7192. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7193. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7194. var img;
  7195. var onload = function () {
  7196. loadedImages[index] = img;
  7197. loadedImages._internalCount++;
  7198. scene._removePendingData(img);
  7199. if (loadedImages._internalCount === 6) {
  7200. onfinish(loadedImages);
  7201. }
  7202. };
  7203. var onerror = function () {
  7204. scene._removePendingData(img);
  7205. if (onErrorCallBack) {
  7206. onErrorCallBack();
  7207. }
  7208. };
  7209. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7210. scene._addPendingData(img);
  7211. };
  7212. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7213. if (onError === void 0) { onError = null; }
  7214. var loadedImages = [];
  7215. loadedImages._internalCount = 0;
  7216. for (var index = 0; index < 6; index++) {
  7217. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7218. }
  7219. };
  7220. var BufferPointer = (function () {
  7221. function BufferPointer() {
  7222. }
  7223. return BufferPointer;
  7224. }());
  7225. var InstancingAttributeInfo = (function () {
  7226. function InstancingAttributeInfo() {
  7227. }
  7228. return InstancingAttributeInfo;
  7229. }());
  7230. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7231. var EngineCapabilities = (function () {
  7232. function EngineCapabilities() {
  7233. }
  7234. return EngineCapabilities;
  7235. }());
  7236. BABYLON.EngineCapabilities = EngineCapabilities;
  7237. /**
  7238. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7239. */
  7240. var Engine = (function () {
  7241. /**
  7242. * @constructor
  7243. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7244. * @param {boolean} [antialias] - enable antialias
  7245. * @param options - further options to be sent to the getContext function
  7246. */
  7247. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7248. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7249. var _this = this;
  7250. // Public members
  7251. this.forcePOTTextures = false;
  7252. this.isFullscreen = false;
  7253. this.isPointerLock = false;
  7254. this.cullBackFaces = true;
  7255. this.renderEvenInBackground = true;
  7256. this.preventCacheWipeBetweenFrames = false;
  7257. // To enable/disable IDB support and avoid XHR on .manifest
  7258. this.enableOfflineSupport = BABYLON.Database;
  7259. this.scenes = new Array();
  7260. // Observables
  7261. /**
  7262. * Observable event triggered each time the rendering canvas is resized
  7263. */
  7264. this.onResizeObservable = new BABYLON.Observable();
  7265. /**
  7266. * Observable event triggered each time the canvas lost focus
  7267. */
  7268. this.onCanvasBlurObservable = new BABYLON.Observable();
  7269. this._windowIsBackground = false;
  7270. this._webGLVersion = 1.0;
  7271. this._badOS = false;
  7272. this._badDesktopOS = false;
  7273. this._drawCalls = new BABYLON.PerfCounter();
  7274. this._renderingQueueLaunched = false;
  7275. this._activeRenderLoops = [];
  7276. // FPS
  7277. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7278. this._fps = 60;
  7279. this._deltaTime = 0;
  7280. // States
  7281. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7282. this._stencilState = new BABYLON.Internals._StencilState();
  7283. this._alphaState = new BABYLON.Internals._AlphaState();
  7284. this._alphaMode = Engine.ALPHA_DISABLE;
  7285. // Cache
  7286. this._loadedTexturesCache = new Array();
  7287. this._maxTextureChannels = 16;
  7288. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7289. this._compiledEffects = {};
  7290. this._vertexAttribArraysEnabled = [];
  7291. this._uintIndicesCurrentlySet = false;
  7292. this._currentBoundBuffer = new Array();
  7293. this._currentBufferPointers = new Array();
  7294. this._currentInstanceLocations = new Array();
  7295. this._currentInstanceBuffers = new Array();
  7296. this._vaoRecordInProgress = false;
  7297. this._mustWipeVertexAttributes = false;
  7298. // Hardware supported Compressed Textures
  7299. this._texturesSupported = new Array();
  7300. this._onVRFullScreenTriggered = function () {
  7301. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7302. //get the old size before we change
  7303. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7304. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7305. //get the width and height, change the render size
  7306. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7307. var width, height;
  7308. _this.setHardwareScalingLevel(1);
  7309. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7310. }
  7311. else {
  7312. //When the specs are implemented, need to uncomment this.
  7313. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7314. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7315. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7316. _this._vrDisplayEnabled = undefined;
  7317. }
  7318. };
  7319. var canvas;
  7320. Engine.Instances.push(this);
  7321. options = options || {};
  7322. if (canvasOrContext.getContext) {
  7323. canvas = canvasOrContext;
  7324. this._renderingCanvas = canvas;
  7325. if (antialias != null) {
  7326. options.antialias = antialias;
  7327. }
  7328. if (options.preserveDrawingBuffer === undefined) {
  7329. options.preserveDrawingBuffer = false;
  7330. }
  7331. if (options.audioEngine === undefined) {
  7332. options.audioEngine = true;
  7333. }
  7334. if (options.stencil === undefined) {
  7335. options.stencil = true;
  7336. }
  7337. // GL
  7338. if (!options.disableWebGL2Support) {
  7339. try {
  7340. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7341. if (this._gl) {
  7342. this._webGLVersion = 2.0;
  7343. }
  7344. }
  7345. catch (e) {
  7346. // Do nothing
  7347. }
  7348. }
  7349. if (!this._gl) {
  7350. if (!canvas) {
  7351. throw new Error("The provided canvas is null or undefined.");
  7352. }
  7353. try {
  7354. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7355. }
  7356. catch (e) {
  7357. throw new Error("WebGL not supported");
  7358. }
  7359. }
  7360. if (!this._gl) {
  7361. throw new Error("WebGL not supported");
  7362. }
  7363. this._onBlur = function () {
  7364. _this._performanceMonitor.disable();
  7365. _this._windowIsBackground = true;
  7366. };
  7367. this._onFocus = function () {
  7368. _this._performanceMonitor.enable();
  7369. _this._windowIsBackground = false;
  7370. };
  7371. this._onCanvasBlur = function () {
  7372. _this.onCanvasBlurObservable.notifyObservers(_this);
  7373. };
  7374. window.addEventListener("blur", this._onBlur);
  7375. window.addEventListener("focus", this._onFocus);
  7376. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7377. }
  7378. else {
  7379. this._gl = canvasOrContext;
  7380. this._renderingCanvas = this._gl.canvas;
  7381. if (this._gl.renderbufferStorageMultisample) {
  7382. this._webGLVersion = 2.0;
  7383. }
  7384. options.stencil = this._gl.getContextAttributes().stencil;
  7385. }
  7386. // Viewport
  7387. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7388. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7389. this.resize();
  7390. // Caps
  7391. this._isStencilEnable = options.stencil;
  7392. this._caps = new EngineCapabilities();
  7393. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7394. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7395. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7396. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7397. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7398. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7399. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7400. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7401. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7402. // Infos
  7403. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7404. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7405. if (rendererInfo != null) {
  7406. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7407. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7408. }
  7409. if (!this._glVendor) {
  7410. this._glVendor = "Unknown vendor";
  7411. }
  7412. if (!this._glRenderer) {
  7413. this._glRenderer = "Unknown renderer";
  7414. }
  7415. // Constants
  7416. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  7417. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  7418. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  7419. this._gl.DEPTH24_STENCIL8 = 35056;
  7420. // Extensions
  7421. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7422. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7423. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7424. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7425. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7426. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7427. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7428. 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');
  7429. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7430. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7431. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7432. this._caps.highPrecisionShaderSupported = true;
  7433. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7434. // Checks if some of the format renders first to allow the use of webgl inspector.
  7435. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7436. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7437. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7438. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7439. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7440. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7441. if (this._webGLVersion > 1) {
  7442. this._gl.HALF_FLOAT_OES = 0x140B;
  7443. }
  7444. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7445. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7446. // Vertex array object
  7447. if (this._webGLVersion > 1) {
  7448. this._caps.vertexArrayObject = true;
  7449. }
  7450. else {
  7451. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7452. if (vertexArrayObjectExtension != null) {
  7453. this._caps.vertexArrayObject = true;
  7454. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7455. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7456. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7457. }
  7458. else {
  7459. this._caps.vertexArrayObject = false;
  7460. }
  7461. }
  7462. // Instances count
  7463. if (this._webGLVersion > 1) {
  7464. this._caps.instancedArrays = true;
  7465. }
  7466. else {
  7467. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7468. if (instanceExtension != null) {
  7469. this._caps.instancedArrays = true;
  7470. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7471. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7472. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7473. }
  7474. else {
  7475. this._caps.instancedArrays = false;
  7476. }
  7477. }
  7478. // Intelligently add supported compressed formats in order to check for.
  7479. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7480. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7481. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7482. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7483. if (this._caps.astc)
  7484. this.texturesSupported.push('-astc.ktx');
  7485. if (this._caps.s3tc)
  7486. this.texturesSupported.push('-dxt.ktx');
  7487. if (this._caps.pvrtc)
  7488. this.texturesSupported.push('-pvrtc.ktx');
  7489. if (this._caps.etc2)
  7490. this.texturesSupported.push('-etc2.ktx');
  7491. if (this._caps.etc1)
  7492. this.texturesSupported.push('-etc1.ktx');
  7493. if (this._gl.getShaderPrecisionFormat) {
  7494. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7495. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7496. }
  7497. // Depth buffer
  7498. this.setDepthBuffer(true);
  7499. this.setDepthFunctionToLessOrEqual();
  7500. this.setDepthWrite(true);
  7501. if (canvas) {
  7502. // Fullscreen
  7503. this._onFullscreenChange = function () {
  7504. if (document.fullscreen !== undefined) {
  7505. _this.isFullscreen = document.fullscreen;
  7506. }
  7507. else if (document.mozFullScreen !== undefined) {
  7508. _this.isFullscreen = document.mozFullScreen;
  7509. }
  7510. else if (document.webkitIsFullScreen !== undefined) {
  7511. _this.isFullscreen = document.webkitIsFullScreen;
  7512. }
  7513. else if (document.msIsFullScreen !== undefined) {
  7514. _this.isFullscreen = document.msIsFullScreen;
  7515. }
  7516. // Pointer lock
  7517. if (_this.isFullscreen && _this._pointerLockRequested) {
  7518. canvas.requestPointerLock = canvas.requestPointerLock ||
  7519. canvas.msRequestPointerLock ||
  7520. canvas.mozRequestPointerLock ||
  7521. canvas.webkitRequestPointerLock;
  7522. if (canvas.requestPointerLock) {
  7523. canvas.requestPointerLock();
  7524. }
  7525. }
  7526. };
  7527. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7528. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7529. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7530. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7531. // Pointer lock
  7532. this._onPointerLockChange = function () {
  7533. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7534. document.webkitPointerLockElement === canvas ||
  7535. document.msPointerLockElement === canvas ||
  7536. document.pointerLockElement === canvas);
  7537. };
  7538. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7539. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7540. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7541. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7542. }
  7543. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7544. Engine.audioEngine = new BABYLON.AudioEngine();
  7545. }
  7546. // Prepare buffer pointers
  7547. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7548. this._currentBufferPointers[i] = new BufferPointer();
  7549. }
  7550. //Load WebVR Devices
  7551. if (options.autoEnableWebVR) {
  7552. this.initWebVR();
  7553. }
  7554. //Detect if we are running on a faulty buggy OS.
  7555. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7556. //Detect if we are running on a faulty buggy desktop OS.
  7557. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7558. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7559. }
  7560. Object.defineProperty(Engine, "LastCreatedEngine", {
  7561. get: function () {
  7562. if (Engine.Instances.length === 0) {
  7563. return null;
  7564. }
  7565. return Engine.Instances[Engine.Instances.length - 1];
  7566. },
  7567. enumerable: true,
  7568. configurable: true
  7569. });
  7570. Object.defineProperty(Engine, "LastCreatedScene", {
  7571. get: function () {
  7572. var lastCreatedEngine = Engine.LastCreatedEngine;
  7573. if (!lastCreatedEngine) {
  7574. return null;
  7575. }
  7576. if (lastCreatedEngine.scenes.length === 0) {
  7577. return null;
  7578. }
  7579. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7580. },
  7581. enumerable: true,
  7582. configurable: true
  7583. });
  7584. /**
  7585. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7586. */
  7587. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7588. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7589. var engine = Engine.Instances[engineIndex];
  7590. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7591. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7592. }
  7593. }
  7594. };
  7595. Object.defineProperty(Engine, "NEVER", {
  7596. get: function () {
  7597. return Engine._NEVER;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Object.defineProperty(Engine, "ALWAYS", {
  7603. get: function () {
  7604. return Engine._ALWAYS;
  7605. },
  7606. enumerable: true,
  7607. configurable: true
  7608. });
  7609. Object.defineProperty(Engine, "LESS", {
  7610. get: function () {
  7611. return Engine._LESS;
  7612. },
  7613. enumerable: true,
  7614. configurable: true
  7615. });
  7616. Object.defineProperty(Engine, "EQUAL", {
  7617. get: function () {
  7618. return Engine._EQUAL;
  7619. },
  7620. enumerable: true,
  7621. configurable: true
  7622. });
  7623. Object.defineProperty(Engine, "LEQUAL", {
  7624. get: function () {
  7625. return Engine._LEQUAL;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(Engine, "GREATER", {
  7631. get: function () {
  7632. return Engine._GREATER;
  7633. },
  7634. enumerable: true,
  7635. configurable: true
  7636. });
  7637. Object.defineProperty(Engine, "GEQUAL", {
  7638. get: function () {
  7639. return Engine._GEQUAL;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(Engine, "NOTEQUAL", {
  7645. get: function () {
  7646. return Engine._NOTEQUAL;
  7647. },
  7648. enumerable: true,
  7649. configurable: true
  7650. });
  7651. Object.defineProperty(Engine, "KEEP", {
  7652. get: function () {
  7653. return Engine._KEEP;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(Engine, "REPLACE", {
  7659. get: function () {
  7660. return Engine._REPLACE;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. Object.defineProperty(Engine, "INCR", {
  7666. get: function () {
  7667. return Engine._INCR;
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(Engine, "DECR", {
  7673. get: function () {
  7674. return Engine._DECR;
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. Object.defineProperty(Engine, "INVERT", {
  7680. get: function () {
  7681. return Engine._INVERT;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(Engine, "INCR_WRAP", {
  7687. get: function () {
  7688. return Engine._INCR_WRAP;
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(Engine, "DECR_WRAP", {
  7694. get: function () {
  7695. return Engine._DECR_WRAP;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7701. get: function () {
  7702. return Engine._ALPHA_DISABLE;
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7708. get: function () {
  7709. return Engine._ALPHA_ONEONE;
  7710. },
  7711. enumerable: true,
  7712. configurable: true
  7713. });
  7714. Object.defineProperty(Engine, "ALPHA_ADD", {
  7715. get: function () {
  7716. return Engine._ALPHA_ADD;
  7717. },
  7718. enumerable: true,
  7719. configurable: true
  7720. });
  7721. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7722. get: function () {
  7723. return Engine._ALPHA_COMBINE;
  7724. },
  7725. enumerable: true,
  7726. configurable: true
  7727. });
  7728. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7729. get: function () {
  7730. return Engine._ALPHA_SUBTRACT;
  7731. },
  7732. enumerable: true,
  7733. configurable: true
  7734. });
  7735. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7736. get: function () {
  7737. return Engine._ALPHA_MULTIPLY;
  7738. },
  7739. enumerable: true,
  7740. configurable: true
  7741. });
  7742. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7743. get: function () {
  7744. return Engine._ALPHA_MAXIMIZED;
  7745. },
  7746. enumerable: true,
  7747. configurable: true
  7748. });
  7749. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7750. get: function () {
  7751. return Engine._ALPHA_PREMULTIPLIED;
  7752. },
  7753. enumerable: true,
  7754. configurable: true
  7755. });
  7756. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7757. get: function () {
  7758. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7759. },
  7760. enumerable: true,
  7761. configurable: true
  7762. });
  7763. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7764. get: function () {
  7765. return Engine._ALPHA_INTERPOLATE;
  7766. },
  7767. enumerable: true,
  7768. configurable: true
  7769. });
  7770. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7771. get: function () {
  7772. return Engine._ALPHA_SCREENMODE;
  7773. },
  7774. enumerable: true,
  7775. configurable: true
  7776. });
  7777. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7778. get: function () {
  7779. return Engine._DELAYLOADSTATE_NONE;
  7780. },
  7781. enumerable: true,
  7782. configurable: true
  7783. });
  7784. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7785. get: function () {
  7786. return Engine._DELAYLOADSTATE_LOADED;
  7787. },
  7788. enumerable: true,
  7789. configurable: true
  7790. });
  7791. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7792. get: function () {
  7793. return Engine._DELAYLOADSTATE_LOADING;
  7794. },
  7795. enumerable: true,
  7796. configurable: true
  7797. });
  7798. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7799. get: function () {
  7800. return Engine._DELAYLOADSTATE_NOTLOADED;
  7801. },
  7802. enumerable: true,
  7803. configurable: true
  7804. });
  7805. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7806. get: function () {
  7807. return Engine._TEXTUREFORMAT_ALPHA;
  7808. },
  7809. enumerable: true,
  7810. configurable: true
  7811. });
  7812. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7813. get: function () {
  7814. return Engine._TEXTUREFORMAT_LUMINANCE;
  7815. },
  7816. enumerable: true,
  7817. configurable: true
  7818. });
  7819. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7820. get: function () {
  7821. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7822. },
  7823. enumerable: true,
  7824. configurable: true
  7825. });
  7826. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7827. get: function () {
  7828. return Engine._TEXTUREFORMAT_RGB;
  7829. },
  7830. enumerable: true,
  7831. configurable: true
  7832. });
  7833. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7834. get: function () {
  7835. return Engine._TEXTUREFORMAT_RGBA;
  7836. },
  7837. enumerable: true,
  7838. configurable: true
  7839. });
  7840. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7841. get: function () {
  7842. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7843. },
  7844. enumerable: true,
  7845. configurable: true
  7846. });
  7847. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7848. get: function () {
  7849. return Engine._TEXTURETYPE_FLOAT;
  7850. },
  7851. enumerable: true,
  7852. configurable: true
  7853. });
  7854. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7855. get: function () {
  7856. return Engine._TEXTURETYPE_HALF_FLOAT;
  7857. },
  7858. enumerable: true,
  7859. configurable: true
  7860. });
  7861. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7862. get: function () {
  7863. return Engine._SCALEMODE_FLOOR;
  7864. },
  7865. enumerable: true,
  7866. configurable: true
  7867. });
  7868. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7869. get: function () {
  7870. return Engine._SCALEMODE_NEAREST;
  7871. },
  7872. enumerable: true,
  7873. configurable: true
  7874. });
  7875. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7876. get: function () {
  7877. return Engine._SCALEMODE_CEILING;
  7878. },
  7879. enumerable: true,
  7880. configurable: true
  7881. });
  7882. Object.defineProperty(Engine, "Version", {
  7883. get: function () {
  7884. return "3.1-alpha";
  7885. },
  7886. enumerable: true,
  7887. configurable: true
  7888. });
  7889. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  7890. get: function () {
  7891. return this._webGLVersion < 2 || this.forcePOTTextures;
  7892. },
  7893. enumerable: true,
  7894. configurable: true
  7895. });
  7896. Object.defineProperty(Engine.prototype, "badOS", {
  7897. get: function () {
  7898. return this._badOS;
  7899. },
  7900. enumerable: true,
  7901. configurable: true
  7902. });
  7903. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  7904. get: function () {
  7905. return this._badDesktopOS;
  7906. },
  7907. enumerable: true,
  7908. configurable: true
  7909. });
  7910. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7911. get: function () {
  7912. return this._texturesSupported;
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7918. get: function () {
  7919. return this._textureFormatInUse;
  7920. },
  7921. enumerable: true,
  7922. configurable: true
  7923. });
  7924. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7925. // Empty texture
  7926. get: function () {
  7927. if (!this._emptyTexture) {
  7928. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7929. }
  7930. return this._emptyTexture;
  7931. },
  7932. enumerable: true,
  7933. configurable: true
  7934. });
  7935. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7936. get: function () {
  7937. if (!this._emptyCubeTexture) {
  7938. var faceData = new Uint8Array(4);
  7939. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7940. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7941. }
  7942. return this._emptyCubeTexture;
  7943. },
  7944. enumerable: true,
  7945. configurable: true
  7946. });
  7947. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7948. get: function () {
  7949. return this._webGLVersion;
  7950. },
  7951. enumerable: true,
  7952. configurable: true
  7953. });
  7954. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7955. /**
  7956. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7957. */
  7958. get: function () {
  7959. return this._isStencilEnable;
  7960. },
  7961. enumerable: true,
  7962. configurable: true
  7963. });
  7964. Engine.prototype._prepareWorkingCanvas = function () {
  7965. if (this._workingCanvas) {
  7966. return;
  7967. }
  7968. this._workingCanvas = document.createElement("canvas");
  7969. this._workingContext = this._workingCanvas.getContext("2d");
  7970. };
  7971. Engine.prototype.resetTextureCache = function () {
  7972. for (var index = 0; index < this._maxTextureChannels; index++) {
  7973. this._activeTexturesCache[index] = null;
  7974. }
  7975. };
  7976. Engine.prototype.getGlInfo = function () {
  7977. return {
  7978. vendor: this._glVendor,
  7979. renderer: this._glRenderer,
  7980. version: this._glVersion
  7981. };
  7982. };
  7983. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7984. if (useScreen === void 0) { useScreen = false; }
  7985. var viewport = camera.viewport;
  7986. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7987. };
  7988. Engine.prototype.getRenderWidth = function (useScreen) {
  7989. if (useScreen === void 0) { useScreen = false; }
  7990. if (!useScreen && this._currentRenderTarget) {
  7991. return this._currentRenderTarget._width;
  7992. }
  7993. return this._gl.drawingBufferWidth;
  7994. };
  7995. Engine.prototype.getRenderHeight = function (useScreen) {
  7996. if (useScreen === void 0) { useScreen = false; }
  7997. if (!useScreen && this._currentRenderTarget) {
  7998. return this._currentRenderTarget._height;
  7999. }
  8000. return this._gl.drawingBufferHeight;
  8001. };
  8002. Engine.prototype.getRenderingCanvas = function () {
  8003. return this._renderingCanvas;
  8004. };
  8005. Engine.prototype.getRenderingCanvasClientRect = function () {
  8006. return this._renderingCanvas.getBoundingClientRect();
  8007. };
  8008. Engine.prototype.setHardwareScalingLevel = function (level) {
  8009. this._hardwareScalingLevel = level;
  8010. this.resize();
  8011. };
  8012. Engine.prototype.getHardwareScalingLevel = function () {
  8013. return this._hardwareScalingLevel;
  8014. };
  8015. Engine.prototype.getLoadedTexturesCache = function () {
  8016. return this._loadedTexturesCache;
  8017. };
  8018. Engine.prototype.getCaps = function () {
  8019. return this._caps;
  8020. };
  8021. Object.defineProperty(Engine.prototype, "drawCalls", {
  8022. get: function () {
  8023. return this._drawCalls.current;
  8024. },
  8025. enumerable: true,
  8026. configurable: true
  8027. });
  8028. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8029. get: function () {
  8030. return this._drawCalls;
  8031. },
  8032. enumerable: true,
  8033. configurable: true
  8034. });
  8035. Engine.prototype.getDepthFunction = function () {
  8036. return this._depthCullingState.depthFunc;
  8037. };
  8038. Engine.prototype.setDepthFunction = function (depthFunc) {
  8039. this._depthCullingState.depthFunc = depthFunc;
  8040. };
  8041. Engine.prototype.setDepthFunctionToGreater = function () {
  8042. this._depthCullingState.depthFunc = this._gl.GREATER;
  8043. };
  8044. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8045. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8046. };
  8047. Engine.prototype.setDepthFunctionToLess = function () {
  8048. this._depthCullingState.depthFunc = this._gl.LESS;
  8049. };
  8050. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8051. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8052. };
  8053. Engine.prototype.getStencilBuffer = function () {
  8054. return this._stencilState.stencilTest;
  8055. };
  8056. Engine.prototype.setStencilBuffer = function (enable) {
  8057. this._stencilState.stencilTest = enable;
  8058. };
  8059. Engine.prototype.getStencilMask = function () {
  8060. return this._stencilState.stencilMask;
  8061. };
  8062. Engine.prototype.setStencilMask = function (mask) {
  8063. this._stencilState.stencilMask = mask;
  8064. };
  8065. Engine.prototype.getStencilFunction = function () {
  8066. return this._stencilState.stencilFunc;
  8067. };
  8068. Engine.prototype.getStencilFunctionReference = function () {
  8069. return this._stencilState.stencilFuncRef;
  8070. };
  8071. Engine.prototype.getStencilFunctionMask = function () {
  8072. return this._stencilState.stencilFuncMask;
  8073. };
  8074. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8075. this._stencilState.stencilFunc = stencilFunc;
  8076. };
  8077. Engine.prototype.setStencilFunctionReference = function (reference) {
  8078. this._stencilState.stencilFuncRef = reference;
  8079. };
  8080. Engine.prototype.setStencilFunctionMask = function (mask) {
  8081. this._stencilState.stencilFuncMask = mask;
  8082. };
  8083. Engine.prototype.getStencilOperationFail = function () {
  8084. return this._stencilState.stencilOpStencilFail;
  8085. };
  8086. Engine.prototype.getStencilOperationDepthFail = function () {
  8087. return this._stencilState.stencilOpDepthFail;
  8088. };
  8089. Engine.prototype.getStencilOperationPass = function () {
  8090. return this._stencilState.stencilOpStencilDepthPass;
  8091. };
  8092. Engine.prototype.setStencilOperationFail = function (operation) {
  8093. this._stencilState.stencilOpStencilFail = operation;
  8094. };
  8095. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8096. this._stencilState.stencilOpDepthFail = operation;
  8097. };
  8098. Engine.prototype.setStencilOperationPass = function (operation) {
  8099. this._stencilState.stencilOpStencilDepthPass = operation;
  8100. };
  8101. Engine.prototype.setDitheringState = function (value) {
  8102. if (value) {
  8103. this._gl.enable(this._gl.DITHER);
  8104. }
  8105. else {
  8106. this._gl.disable(this._gl.DITHER);
  8107. }
  8108. };
  8109. /**
  8110. * stop executing a render loop function and remove it from the execution array
  8111. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8112. */
  8113. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8114. if (!renderFunction) {
  8115. this._activeRenderLoops = [];
  8116. return;
  8117. }
  8118. var index = this._activeRenderLoops.indexOf(renderFunction);
  8119. if (index >= 0) {
  8120. this._activeRenderLoops.splice(index, 1);
  8121. }
  8122. };
  8123. Engine.prototype._renderLoop = function () {
  8124. var shouldRender = true;
  8125. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8126. shouldRender = false;
  8127. }
  8128. if (shouldRender) {
  8129. // Start new frame
  8130. this.beginFrame();
  8131. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8132. var renderFunction = this._activeRenderLoops[index];
  8133. renderFunction();
  8134. }
  8135. // Present
  8136. this.endFrame();
  8137. }
  8138. if (this._activeRenderLoops.length > 0) {
  8139. // Register new frame
  8140. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8141. }
  8142. else {
  8143. this._renderingQueueLaunched = false;
  8144. }
  8145. };
  8146. /**
  8147. * Register and execute a render loop. The engine can have more than one render function.
  8148. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8149. * @example
  8150. * engine.runRenderLoop(function () {
  8151. * scene.render()
  8152. * })
  8153. */
  8154. Engine.prototype.runRenderLoop = function (renderFunction) {
  8155. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8156. return;
  8157. }
  8158. this._activeRenderLoops.push(renderFunction);
  8159. if (!this._renderingQueueLaunched) {
  8160. this._renderingQueueLaunched = true;
  8161. this._bindedRenderFunction = this._renderLoop.bind(this);
  8162. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8163. }
  8164. };
  8165. /**
  8166. * Toggle full screen mode.
  8167. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8168. * @param {any} options - an options object to be sent to the requestFullscreen function
  8169. */
  8170. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8171. if (this.isFullscreen) {
  8172. BABYLON.Tools.ExitFullscreen();
  8173. }
  8174. else {
  8175. this._pointerLockRequested = requestPointerLock;
  8176. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8177. }
  8178. };
  8179. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8180. if (stencil === void 0) { stencil = false; }
  8181. this.applyStates();
  8182. var mode = 0;
  8183. if (backBuffer && color) {
  8184. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8185. mode |= this._gl.COLOR_BUFFER_BIT;
  8186. }
  8187. if (depth) {
  8188. this._gl.clearDepth(1.0);
  8189. mode |= this._gl.DEPTH_BUFFER_BIT;
  8190. }
  8191. if (stencil) {
  8192. this._gl.clearStencil(0);
  8193. mode |= this._gl.STENCIL_BUFFER_BIT;
  8194. }
  8195. this._gl.clear(mode);
  8196. };
  8197. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8198. var gl = this._gl;
  8199. // Save state
  8200. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8201. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8202. // Change state
  8203. gl.enable(gl.SCISSOR_TEST);
  8204. gl.scissor(x, y, width, height);
  8205. // Clear
  8206. this.clear(clearColor, true, true, true);
  8207. // Restore state
  8208. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8209. if (curScissor === true) {
  8210. gl.enable(gl.SCISSOR_TEST);
  8211. }
  8212. else {
  8213. gl.disable(gl.SCISSOR_TEST);
  8214. }
  8215. };
  8216. /**
  8217. * Set the WebGL's viewport
  8218. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8219. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8220. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8221. */
  8222. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8223. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8224. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8225. var x = viewport.x || 0;
  8226. var y = viewport.y || 0;
  8227. this._cachedViewport = viewport;
  8228. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8229. };
  8230. /**
  8231. * Directly set the WebGL Viewport
  8232. * The x, y, width & height are directly passed to the WebGL call
  8233. * @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.
  8234. */
  8235. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8236. var currentViewport = this._cachedViewport;
  8237. this._cachedViewport = null;
  8238. this._gl.viewport(x, y, width, height);
  8239. return currentViewport;
  8240. };
  8241. Engine.prototype.beginFrame = function () {
  8242. this._measureFps();
  8243. };
  8244. Engine.prototype.endFrame = function () {
  8245. //force a flush in case we are using a bad OS.
  8246. if (this._badOS) {
  8247. this.flushFramebuffer();
  8248. }
  8249. //submit frame to the vr device, if enabled
  8250. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8251. this._vrDisplayEnabled.submitFrame();
  8252. }
  8253. };
  8254. /**
  8255. * resize the view according to the canvas' size.
  8256. * @example
  8257. * window.addEventListener("resize", function () {
  8258. * engine.resize();
  8259. * });
  8260. */
  8261. Engine.prototype.resize = function () {
  8262. // We're not resizing the size of the canvas while in VR mode & presenting
  8263. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8264. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8265. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8266. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8267. }
  8268. };
  8269. /**
  8270. * force a specific size of the canvas
  8271. * @param {number} width - the new canvas' width
  8272. * @param {number} height - the new canvas' height
  8273. */
  8274. Engine.prototype.setSize = function (width, height) {
  8275. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8276. return;
  8277. }
  8278. this._renderingCanvas.width = width;
  8279. this._renderingCanvas.height = height;
  8280. for (var index = 0; index < this.scenes.length; index++) {
  8281. var scene = this.scenes[index];
  8282. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8283. var cam = scene.cameras[camIndex];
  8284. cam._currentRenderId = 0;
  8285. }
  8286. }
  8287. if (this.onResizeObservable.hasObservers) {
  8288. this.onResizeObservable.notifyObservers(this);
  8289. }
  8290. };
  8291. //WebVR functions
  8292. Engine.prototype.isVRDevicePresent = function (callback) {
  8293. this.getVRDevice(null, function (device) {
  8294. callback(device !== null);
  8295. });
  8296. };
  8297. Engine.prototype.getVRDevice = function (name, callback) {
  8298. if (!this.vrDisplaysPromise) {
  8299. callback(null);
  8300. return;
  8301. }
  8302. this.vrDisplaysPromise.then(function (devices) {
  8303. if (devices.length > 0) {
  8304. if (name) {
  8305. var found = devices.some(function (device) {
  8306. if (device.displayName === name) {
  8307. callback(device);
  8308. return true;
  8309. }
  8310. else {
  8311. return false;
  8312. }
  8313. });
  8314. if (!found) {
  8315. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8316. callback(devices[0]);
  8317. }
  8318. }
  8319. else {
  8320. //choose the first one
  8321. callback(devices[0]);
  8322. }
  8323. }
  8324. else {
  8325. BABYLON.Tools.Error("No WebVR devices found!");
  8326. callback(null);
  8327. }
  8328. });
  8329. };
  8330. Engine.prototype.initWebVR = function () {
  8331. if (!this.vrDisplaysPromise) {
  8332. this._getVRDisplays();
  8333. }
  8334. };
  8335. Engine.prototype.enableVR = function (vrDevice) {
  8336. this._vrDisplayEnabled = vrDevice;
  8337. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8338. };
  8339. Engine.prototype.disableVR = function () {
  8340. if (this._vrDisplayEnabled) {
  8341. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8342. }
  8343. };
  8344. Engine.prototype._getVRDisplays = function () {
  8345. var _this = this;
  8346. var getWebVRDevices = function (devices) {
  8347. var size = devices.length;
  8348. var i = 0;
  8349. _this._vrDisplays = devices.filter(function (device) {
  8350. return devices[i] instanceof VRDisplay;
  8351. });
  8352. return _this._vrDisplays;
  8353. };
  8354. //using a key due to typescript
  8355. if (navigator.getVRDisplays) {
  8356. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8357. }
  8358. };
  8359. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8360. if (this._currentRenderTarget) {
  8361. this.unBindFramebuffer(this._currentRenderTarget);
  8362. }
  8363. this._currentRenderTarget = texture;
  8364. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8365. var gl = this._gl;
  8366. if (texture.isCube) {
  8367. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8368. }
  8369. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8370. this.wipeCaches();
  8371. };
  8372. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8373. if (this._currentFramebuffer !== framebuffer) {
  8374. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8375. this._currentFramebuffer = framebuffer;
  8376. }
  8377. };
  8378. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8379. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8380. this._currentRenderTarget = null;
  8381. // If MSAA, we need to bitblt back to main texture
  8382. var gl = this._gl;
  8383. if (texture._MSAAFramebuffer) {
  8384. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8385. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8386. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8387. }
  8388. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8389. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8390. gl.generateMipmap(gl.TEXTURE_2D);
  8391. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8392. }
  8393. if (onBeforeUnbind) {
  8394. if (texture._MSAAFramebuffer) {
  8395. // Bind the correct framebuffer
  8396. this.bindUnboundFramebuffer(texture._framebuffer);
  8397. }
  8398. onBeforeUnbind();
  8399. }
  8400. this.bindUnboundFramebuffer(null);
  8401. };
  8402. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8403. if (texture.generateMipMaps) {
  8404. var gl = this._gl;
  8405. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8406. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8407. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8408. }
  8409. };
  8410. Engine.prototype.flushFramebuffer = function () {
  8411. this._gl.flush();
  8412. };
  8413. Engine.prototype.restoreDefaultFramebuffer = function () {
  8414. if (this._currentRenderTarget) {
  8415. this.unBindFramebuffer(this._currentRenderTarget);
  8416. }
  8417. else {
  8418. this.bindUnboundFramebuffer(null);
  8419. }
  8420. if (this._cachedViewport) {
  8421. this.setViewport(this._cachedViewport);
  8422. }
  8423. this.wipeCaches();
  8424. };
  8425. // UBOs
  8426. Engine.prototype.createUniformBuffer = function (elements) {
  8427. var ubo = this._gl.createBuffer();
  8428. this.bindUniformBuffer(ubo);
  8429. if (elements instanceof Float32Array) {
  8430. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8431. }
  8432. else {
  8433. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8434. }
  8435. this.bindUniformBuffer(null);
  8436. ubo.references = 1;
  8437. return ubo;
  8438. };
  8439. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8440. var ubo = this._gl.createBuffer();
  8441. this.bindUniformBuffer(ubo);
  8442. if (elements instanceof Float32Array) {
  8443. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8444. }
  8445. else {
  8446. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8447. }
  8448. this.bindUniformBuffer(null);
  8449. ubo.references = 1;
  8450. return ubo;
  8451. };
  8452. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8453. this.bindUniformBuffer(uniformBuffer);
  8454. if (offset === undefined) {
  8455. offset = 0;
  8456. }
  8457. if (count === undefined) {
  8458. if (elements instanceof Float32Array) {
  8459. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8460. }
  8461. else {
  8462. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8463. }
  8464. }
  8465. else {
  8466. if (elements instanceof Float32Array) {
  8467. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8468. }
  8469. else {
  8470. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8471. }
  8472. }
  8473. this.bindUniformBuffer(null);
  8474. };
  8475. // VBOs
  8476. Engine.prototype._resetVertexBufferBinding = function () {
  8477. this.bindArrayBuffer(null);
  8478. this._cachedVertexBuffers = null;
  8479. };
  8480. Engine.prototype.createVertexBuffer = function (vertices) {
  8481. var vbo = this._gl.createBuffer();
  8482. this.bindArrayBuffer(vbo);
  8483. if (vertices instanceof Float32Array) {
  8484. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8485. }
  8486. else {
  8487. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8488. }
  8489. this._resetVertexBufferBinding();
  8490. vbo.references = 1;
  8491. return vbo;
  8492. };
  8493. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8494. var vbo = this._gl.createBuffer();
  8495. this.bindArrayBuffer(vbo);
  8496. if (vertices instanceof Float32Array) {
  8497. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8498. }
  8499. else {
  8500. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8501. }
  8502. this._resetVertexBufferBinding();
  8503. vbo.references = 1;
  8504. return vbo;
  8505. };
  8506. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8507. this.bindArrayBuffer(vertexBuffer);
  8508. if (offset === undefined) {
  8509. offset = 0;
  8510. }
  8511. if (count === undefined) {
  8512. if (vertices instanceof Float32Array) {
  8513. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8514. }
  8515. else {
  8516. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8517. }
  8518. }
  8519. else {
  8520. if (vertices instanceof Float32Array) {
  8521. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8522. }
  8523. else {
  8524. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8525. }
  8526. }
  8527. this._resetVertexBufferBinding();
  8528. };
  8529. Engine.prototype._resetIndexBufferBinding = function () {
  8530. this.bindIndexBuffer(null);
  8531. this._cachedIndexBuffer = null;
  8532. };
  8533. Engine.prototype.createIndexBuffer = function (indices) {
  8534. var vbo = this._gl.createBuffer();
  8535. this.bindIndexBuffer(vbo);
  8536. // Check for 32 bits indices
  8537. var arrayBuffer;
  8538. var need32Bits = false;
  8539. if (indices instanceof Uint16Array) {
  8540. arrayBuffer = indices;
  8541. }
  8542. else {
  8543. //check 32 bit support
  8544. if (this._caps.uintIndices) {
  8545. if (indices instanceof Uint32Array) {
  8546. arrayBuffer = indices;
  8547. need32Bits = true;
  8548. }
  8549. else {
  8550. //number[] or Int32Array, check if 32 bit is necessary
  8551. for (var index = 0; index < indices.length; index++) {
  8552. if (indices[index] > 65535) {
  8553. need32Bits = true;
  8554. break;
  8555. }
  8556. }
  8557. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8558. }
  8559. }
  8560. else {
  8561. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8562. arrayBuffer = new Uint16Array(indices);
  8563. }
  8564. }
  8565. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8566. this._resetIndexBufferBinding();
  8567. vbo.references = 1;
  8568. vbo.is32Bits = need32Bits;
  8569. return vbo;
  8570. };
  8571. Engine.prototype.bindArrayBuffer = function (buffer) {
  8572. if (!this._vaoRecordInProgress) {
  8573. this._unBindVertexArrayObject();
  8574. }
  8575. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8576. };
  8577. Engine.prototype.bindUniformBuffer = function (buffer) {
  8578. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8579. };
  8580. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8581. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8582. };
  8583. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8584. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8585. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8586. };
  8587. ;
  8588. Engine.prototype.bindIndexBuffer = function (buffer) {
  8589. if (!this._vaoRecordInProgress) {
  8590. this._unBindVertexArrayObject();
  8591. }
  8592. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8593. };
  8594. Engine.prototype.bindBuffer = function (buffer, target) {
  8595. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8596. this._gl.bindBuffer(target, buffer);
  8597. this._currentBoundBuffer[target] = buffer;
  8598. }
  8599. };
  8600. Engine.prototype.updateArrayBuffer = function (data) {
  8601. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8602. };
  8603. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8604. var pointer = this._currentBufferPointers[indx];
  8605. var changed = false;
  8606. if (!pointer.active) {
  8607. changed = true;
  8608. pointer.active = true;
  8609. pointer.index = indx;
  8610. pointer.size = size;
  8611. pointer.type = type;
  8612. pointer.normalized = normalized;
  8613. pointer.stride = stride;
  8614. pointer.offset = offset;
  8615. pointer.buffer = buffer;
  8616. }
  8617. else {
  8618. if (pointer.buffer !== buffer) {
  8619. pointer.buffer = buffer;
  8620. changed = true;
  8621. }
  8622. if (pointer.size !== size) {
  8623. pointer.size = size;
  8624. changed = true;
  8625. }
  8626. if (pointer.type !== type) {
  8627. pointer.type = type;
  8628. changed = true;
  8629. }
  8630. if (pointer.normalized !== normalized) {
  8631. pointer.normalized = normalized;
  8632. changed = true;
  8633. }
  8634. if (pointer.stride !== stride) {
  8635. pointer.stride = stride;
  8636. changed = true;
  8637. }
  8638. if (pointer.offset !== offset) {
  8639. pointer.offset = offset;
  8640. changed = true;
  8641. }
  8642. }
  8643. if (changed || this._vaoRecordInProgress) {
  8644. this.bindArrayBuffer(buffer);
  8645. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8646. }
  8647. };
  8648. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8649. if (indexBuffer == null) {
  8650. return;
  8651. }
  8652. if (this._cachedIndexBuffer !== indexBuffer) {
  8653. this._cachedIndexBuffer = indexBuffer;
  8654. this.bindIndexBuffer(indexBuffer);
  8655. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8656. }
  8657. };
  8658. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8659. var attributes = effect.getAttributesNames();
  8660. if (!this._vaoRecordInProgress) {
  8661. this._unBindVertexArrayObject();
  8662. }
  8663. this.unbindAllAttributes();
  8664. for (var index = 0; index < attributes.length; index++) {
  8665. var order = effect.getAttributeLocation(index);
  8666. if (order >= 0) {
  8667. var vertexBuffer = vertexBuffers[attributes[index]];
  8668. if (!vertexBuffer) {
  8669. continue;
  8670. }
  8671. this._gl.enableVertexAttribArray(order);
  8672. if (!this._vaoRecordInProgress) {
  8673. this._vertexAttribArraysEnabled[order] = true;
  8674. }
  8675. var buffer = vertexBuffer.getBuffer();
  8676. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8677. if (vertexBuffer.getIsInstanced()) {
  8678. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8679. if (!this._vaoRecordInProgress) {
  8680. this._currentInstanceLocations.push(order);
  8681. this._currentInstanceBuffers.push(buffer);
  8682. }
  8683. }
  8684. }
  8685. }
  8686. };
  8687. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8688. var vao = this._gl.createVertexArray();
  8689. this._vaoRecordInProgress = true;
  8690. this._gl.bindVertexArray(vao);
  8691. this._mustWipeVertexAttributes = true;
  8692. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8693. this.bindIndexBuffer(indexBuffer);
  8694. this._vaoRecordInProgress = false;
  8695. this._gl.bindVertexArray(null);
  8696. return vao;
  8697. };
  8698. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8699. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8700. this._cachedVertexArrayObject = vertexArrayObject;
  8701. this._gl.bindVertexArray(vertexArrayObject);
  8702. this._cachedVertexBuffers = null;
  8703. this._cachedIndexBuffer = null;
  8704. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8705. this._mustWipeVertexAttributes = true;
  8706. }
  8707. };
  8708. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8709. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8710. this._cachedVertexBuffers = vertexBuffer;
  8711. this._cachedEffectForVertexBuffers = effect;
  8712. var attributesCount = effect.getAttributesCount();
  8713. this._unBindVertexArrayObject();
  8714. this.unbindAllAttributes();
  8715. var offset = 0;
  8716. for (var index = 0; index < attributesCount; index++) {
  8717. if (index < vertexDeclaration.length) {
  8718. var order = effect.getAttributeLocation(index);
  8719. if (order >= 0) {
  8720. this._gl.enableVertexAttribArray(order);
  8721. this._vertexAttribArraysEnabled[order] = true;
  8722. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8723. }
  8724. offset += vertexDeclaration[index] * 4;
  8725. }
  8726. }
  8727. }
  8728. this._bindIndexBufferWithCache(indexBuffer);
  8729. };
  8730. Engine.prototype._unBindVertexArrayObject = function () {
  8731. if (!this._cachedVertexArrayObject) {
  8732. return;
  8733. }
  8734. this._cachedVertexArrayObject = null;
  8735. this._gl.bindVertexArray(null);
  8736. };
  8737. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8738. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8739. this._cachedVertexBuffers = vertexBuffers;
  8740. this._cachedEffectForVertexBuffers = effect;
  8741. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8742. }
  8743. this._bindIndexBufferWithCache(indexBuffer);
  8744. };
  8745. Engine.prototype.unbindInstanceAttributes = function () {
  8746. var boundBuffer;
  8747. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8748. var instancesBuffer = this._currentInstanceBuffers[i];
  8749. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8750. boundBuffer = instancesBuffer;
  8751. this.bindArrayBuffer(instancesBuffer);
  8752. }
  8753. var offsetLocation = this._currentInstanceLocations[i];
  8754. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8755. }
  8756. this._currentInstanceBuffers.length = 0;
  8757. this._currentInstanceLocations.length = 0;
  8758. };
  8759. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8760. this._gl.deleteVertexArray(vao);
  8761. };
  8762. Engine.prototype._releaseBuffer = function (buffer) {
  8763. buffer.references--;
  8764. if (buffer.references === 0) {
  8765. this._gl.deleteBuffer(buffer);
  8766. return true;
  8767. }
  8768. return false;
  8769. };
  8770. Engine.prototype.createInstancesBuffer = function (capacity) {
  8771. var buffer = this._gl.createBuffer();
  8772. buffer.capacity = capacity;
  8773. this.bindArrayBuffer(buffer);
  8774. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8775. return buffer;
  8776. };
  8777. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8778. this._gl.deleteBuffer(buffer);
  8779. };
  8780. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8781. this.bindArrayBuffer(instancesBuffer);
  8782. if (data) {
  8783. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8784. }
  8785. if (offsetLocations[0].index !== undefined) {
  8786. var stride = 0;
  8787. for (var i = 0; i < offsetLocations.length; i++) {
  8788. var ai = offsetLocations[i];
  8789. stride += ai.attributeSize * 4;
  8790. }
  8791. for (var i = 0; i < offsetLocations.length; i++) {
  8792. var ai = offsetLocations[i];
  8793. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8794. this._gl.enableVertexAttribArray(ai.index);
  8795. this._vertexAttribArraysEnabled[ai.index] = true;
  8796. }
  8797. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8798. this._gl.vertexAttribDivisor(ai.index, 1);
  8799. this._currentInstanceLocations.push(ai.index);
  8800. this._currentInstanceBuffers.push(instancesBuffer);
  8801. }
  8802. }
  8803. else {
  8804. for (var index = 0; index < 4; index++) {
  8805. var offsetLocation = offsetLocations[index];
  8806. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8807. this._gl.enableVertexAttribArray(offsetLocation);
  8808. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8809. }
  8810. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8811. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8812. this._currentInstanceLocations.push(offsetLocation);
  8813. this._currentInstanceBuffers.push(instancesBuffer);
  8814. }
  8815. }
  8816. };
  8817. Engine.prototype.applyStates = function () {
  8818. this._depthCullingState.apply(this._gl);
  8819. this._stencilState.apply(this._gl);
  8820. this._alphaState.apply(this._gl);
  8821. };
  8822. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8823. // Apply states
  8824. this.applyStates();
  8825. this._drawCalls.addCount(1, false);
  8826. // Render
  8827. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8828. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8829. if (instancesCount) {
  8830. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8831. return;
  8832. }
  8833. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8834. };
  8835. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8836. // Apply states
  8837. this.applyStates();
  8838. this._drawCalls.addCount(1, false);
  8839. if (instancesCount) {
  8840. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8841. return;
  8842. }
  8843. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8844. };
  8845. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8846. // Apply states
  8847. this.applyStates();
  8848. this._drawCalls.addCount(1, false);
  8849. if (instancesCount) {
  8850. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8851. return;
  8852. }
  8853. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8854. };
  8855. // Shaders
  8856. Engine.prototype._releaseEffect = function (effect) {
  8857. if (this._compiledEffects[effect._key]) {
  8858. delete this._compiledEffects[effect._key];
  8859. if (effect.getProgram()) {
  8860. this._gl.deleteProgram(effect.getProgram());
  8861. }
  8862. }
  8863. };
  8864. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8865. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8866. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8867. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8868. if (this._compiledEffects[name]) {
  8869. var compiledEffect = this._compiledEffects[name];
  8870. if (onCompiled && compiledEffect.isReady()) {
  8871. onCompiled(compiledEffect);
  8872. }
  8873. return compiledEffect;
  8874. }
  8875. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8876. effect._key = name;
  8877. this._compiledEffects[name] = effect;
  8878. return effect;
  8879. };
  8880. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8881. if (uniformsNames === void 0) { uniformsNames = []; }
  8882. if (samplers === void 0) { samplers = []; }
  8883. if (defines === void 0) { defines = ""; }
  8884. return this.createEffect({
  8885. vertex: "particles",
  8886. fragmentElement: fragmentName
  8887. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8888. };
  8889. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8890. context = context || this._gl;
  8891. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8892. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8893. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8894. var shaderProgram = context.createProgram();
  8895. context.attachShader(shaderProgram, vertexShader);
  8896. context.attachShader(shaderProgram, fragmentShader);
  8897. context.linkProgram(shaderProgram);
  8898. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8899. if (!linked) {
  8900. context.validateProgram(shaderProgram);
  8901. var error = context.getProgramInfoLog(shaderProgram);
  8902. if (error) {
  8903. throw new Error(error);
  8904. }
  8905. }
  8906. context.deleteShader(vertexShader);
  8907. context.deleteShader(fragmentShader);
  8908. return shaderProgram;
  8909. };
  8910. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8911. var results = [];
  8912. for (var index = 0; index < uniformsNames.length; index++) {
  8913. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8914. }
  8915. return results;
  8916. };
  8917. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8918. var results = [];
  8919. for (var index = 0; index < attributesNames.length; index++) {
  8920. try {
  8921. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8922. }
  8923. catch (e) {
  8924. results.push(-1);
  8925. }
  8926. }
  8927. return results;
  8928. };
  8929. Engine.prototype.enableEffect = function (effect) {
  8930. // Use program
  8931. this.setProgram(effect.getProgram());
  8932. this._currentEffect = effect;
  8933. if (effect.onBind) {
  8934. effect.onBind(effect);
  8935. }
  8936. effect.onBindObservable.notifyObservers(effect);
  8937. };
  8938. Engine.prototype.setIntArray = function (uniform, array) {
  8939. if (!uniform)
  8940. return;
  8941. this._gl.uniform1iv(uniform, array);
  8942. };
  8943. Engine.prototype.setIntArray2 = function (uniform, array) {
  8944. if (!uniform || array.length % 2 !== 0)
  8945. return;
  8946. this._gl.uniform2iv(uniform, array);
  8947. };
  8948. Engine.prototype.setIntArray3 = function (uniform, array) {
  8949. if (!uniform || array.length % 3 !== 0)
  8950. return;
  8951. this._gl.uniform3iv(uniform, array);
  8952. };
  8953. Engine.prototype.setIntArray4 = function (uniform, array) {
  8954. if (!uniform || array.length % 4 !== 0)
  8955. return;
  8956. this._gl.uniform4iv(uniform, array);
  8957. };
  8958. Engine.prototype.setFloatArray = function (uniform, array) {
  8959. if (!uniform)
  8960. return;
  8961. this._gl.uniform1fv(uniform, array);
  8962. };
  8963. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8964. if (!uniform || array.length % 2 !== 0)
  8965. return;
  8966. this._gl.uniform2fv(uniform, array);
  8967. };
  8968. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8969. if (!uniform || array.length % 3 !== 0)
  8970. return;
  8971. this._gl.uniform3fv(uniform, array);
  8972. };
  8973. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8974. if (!uniform || array.length % 4 !== 0)
  8975. return;
  8976. this._gl.uniform4fv(uniform, array);
  8977. };
  8978. Engine.prototype.setArray = function (uniform, array) {
  8979. if (!uniform)
  8980. return;
  8981. this._gl.uniform1fv(uniform, array);
  8982. };
  8983. Engine.prototype.setArray2 = function (uniform, array) {
  8984. if (!uniform || array.length % 2 !== 0)
  8985. return;
  8986. this._gl.uniform2fv(uniform, array);
  8987. };
  8988. Engine.prototype.setArray3 = function (uniform, array) {
  8989. if (!uniform || array.length % 3 !== 0)
  8990. return;
  8991. this._gl.uniform3fv(uniform, array);
  8992. };
  8993. Engine.prototype.setArray4 = function (uniform, array) {
  8994. if (!uniform || array.length % 4 !== 0)
  8995. return;
  8996. this._gl.uniform4fv(uniform, array);
  8997. };
  8998. Engine.prototype.setMatrices = function (uniform, matrices) {
  8999. if (!uniform)
  9000. return;
  9001. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9002. };
  9003. Engine.prototype.setMatrix = function (uniform, matrix) {
  9004. if (!uniform)
  9005. return;
  9006. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9007. };
  9008. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9009. if (!uniform)
  9010. return;
  9011. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9012. };
  9013. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9014. if (!uniform)
  9015. return;
  9016. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9017. };
  9018. Engine.prototype.setFloat = function (uniform, value) {
  9019. if (!uniform)
  9020. return;
  9021. this._gl.uniform1f(uniform, value);
  9022. };
  9023. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9024. if (!uniform)
  9025. return;
  9026. this._gl.uniform2f(uniform, x, y);
  9027. };
  9028. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9029. if (!uniform)
  9030. return;
  9031. this._gl.uniform3f(uniform, x, y, z);
  9032. };
  9033. Engine.prototype.setBool = function (uniform, bool) {
  9034. if (!uniform)
  9035. return;
  9036. this._gl.uniform1i(uniform, bool);
  9037. };
  9038. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9039. if (!uniform)
  9040. return;
  9041. this._gl.uniform4f(uniform, x, y, z, w);
  9042. };
  9043. Engine.prototype.setColor3 = function (uniform, color3) {
  9044. if (!uniform)
  9045. return;
  9046. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9047. };
  9048. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9049. if (!uniform)
  9050. return;
  9051. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9052. };
  9053. // States
  9054. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9055. if (zOffset === void 0) { zOffset = 0; }
  9056. if (reverseSide === void 0) { reverseSide = false; }
  9057. // Culling
  9058. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9059. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9060. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9061. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9062. if (culling) {
  9063. this._depthCullingState.cullFace = cullFace;
  9064. this._depthCullingState.cull = true;
  9065. }
  9066. else {
  9067. this._depthCullingState.cull = false;
  9068. }
  9069. }
  9070. // Z offset
  9071. this.setZOffset(zOffset);
  9072. };
  9073. Engine.prototype.setZOffset = function (value) {
  9074. this._depthCullingState.zOffset = value;
  9075. };
  9076. Engine.prototype.getZOffset = function () {
  9077. return this._depthCullingState.zOffset;
  9078. };
  9079. Engine.prototype.setDepthBuffer = function (enable) {
  9080. this._depthCullingState.depthTest = enable;
  9081. };
  9082. Engine.prototype.getDepthWrite = function () {
  9083. return this._depthCullingState.depthMask;
  9084. };
  9085. Engine.prototype.setDepthWrite = function (enable) {
  9086. this._depthCullingState.depthMask = enable;
  9087. };
  9088. Engine.prototype.setColorWrite = function (enable) {
  9089. this._gl.colorMask(enable, enable, enable, enable);
  9090. };
  9091. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9092. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9093. };
  9094. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9095. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9096. if (this._alphaMode === mode) {
  9097. return;
  9098. }
  9099. switch (mode) {
  9100. case Engine.ALPHA_DISABLE:
  9101. this._alphaState.alphaBlend = false;
  9102. break;
  9103. case Engine.ALPHA_PREMULTIPLIED:
  9104. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9105. this._alphaState.alphaBlend = true;
  9106. break;
  9107. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9108. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9109. this._alphaState.alphaBlend = true;
  9110. break;
  9111. case Engine.ALPHA_COMBINE:
  9112. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9113. this._alphaState.alphaBlend = true;
  9114. break;
  9115. case Engine.ALPHA_ONEONE:
  9116. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9117. this._alphaState.alphaBlend = true;
  9118. break;
  9119. case Engine.ALPHA_ADD:
  9120. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9121. this._alphaState.alphaBlend = true;
  9122. break;
  9123. case Engine.ALPHA_SUBTRACT:
  9124. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9125. this._alphaState.alphaBlend = true;
  9126. break;
  9127. case Engine.ALPHA_MULTIPLY:
  9128. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9129. this._alphaState.alphaBlend = true;
  9130. break;
  9131. case Engine.ALPHA_MAXIMIZED:
  9132. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9133. this._alphaState.alphaBlend = true;
  9134. break;
  9135. case Engine.ALPHA_INTERPOLATE:
  9136. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9137. this._alphaState.alphaBlend = true;
  9138. break;
  9139. case Engine.ALPHA_SCREENMODE:
  9140. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9141. this._alphaState.alphaBlend = true;
  9142. break;
  9143. }
  9144. if (!noDepthWriteChange) {
  9145. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9146. }
  9147. this._alphaMode = mode;
  9148. };
  9149. Engine.prototype.getAlphaMode = function () {
  9150. return this._alphaMode;
  9151. };
  9152. Engine.prototype.setAlphaTesting = function (enable) {
  9153. this._alphaTest = enable;
  9154. };
  9155. Engine.prototype.getAlphaTesting = function () {
  9156. return !!this._alphaTest;
  9157. };
  9158. // Textures
  9159. Engine.prototype.wipeCaches = function (bruteForce) {
  9160. if (this.preventCacheWipeBetweenFrames) {
  9161. return;
  9162. }
  9163. this.resetTextureCache();
  9164. this._currentEffect = null;
  9165. // 6/8/2017: deltakosh: Should not be required anymore.
  9166. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9167. if (bruteForce) {
  9168. this._stencilState.reset();
  9169. this._depthCullingState.reset();
  9170. this.setDepthFunctionToLessOrEqual();
  9171. this._alphaState.reset();
  9172. }
  9173. this._cachedVertexBuffers = null;
  9174. this._cachedIndexBuffer = null;
  9175. this._cachedEffectForVertexBuffers = null;
  9176. this._unBindVertexArrayObject();
  9177. this.bindIndexBuffer(null);
  9178. this.bindArrayBuffer(null);
  9179. };
  9180. /**
  9181. * Set the compressed texture format to use, based on the formats you have, and the formats
  9182. * supported by the hardware / browser.
  9183. *
  9184. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9185. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9186. * to API arguments needed to compressed textures. This puts the burden on the container
  9187. * generator to house the arcane code for determining these for current & future formats.
  9188. *
  9189. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9190. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9191. *
  9192. * Note: The result of this call is not taken into account when a texture is base64.
  9193. *
  9194. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9195. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9196. *
  9197. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9198. * @returns The extension selected.
  9199. */
  9200. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9201. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9202. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9203. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9204. return this._textureFormatInUse = this._texturesSupported[i];
  9205. }
  9206. }
  9207. }
  9208. // actively set format to nothing, to allow this to be called more than once
  9209. // and possibly fail the 2nd time
  9210. return this._textureFormatInUse = null;
  9211. };
  9212. /**
  9213. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9214. * @param {string} urlArg- This contains one of the following:
  9215. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9216. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9217. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9218. *
  9219. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9220. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9221. * @param {Scene} scene- Needed for loading to the correct scene.
  9222. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9223. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9224. * @param {callback} onError- Optional callback to be called upon failure.
  9225. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9226. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9227. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9228. *
  9229. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9230. */
  9231. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9232. var _this = this;
  9233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9234. if (onLoad === void 0) { onLoad = null; }
  9235. if (onError === void 0) { onError = null; }
  9236. if (buffer === void 0) { buffer = null; }
  9237. var texture = fallBack ? fallBack : this._gl.createTexture();
  9238. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9239. var fromData = url.substr(0, 5) === "data:";
  9240. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9241. // establish the file extension, if possible
  9242. var lastDot = url.lastIndexOf('.');
  9243. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9244. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9245. var isTGA = (extension === ".tga");
  9246. // determine if a ktx file should be substituted
  9247. var isKTX = false;
  9248. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9249. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9250. isKTX = true;
  9251. }
  9252. scene._addPendingData(texture);
  9253. texture.url = url;
  9254. texture.generateMipMaps = !noMipmap;
  9255. texture.references = 1;
  9256. texture.samplingMode = samplingMode;
  9257. texture.onLoadedCallbacks = [];
  9258. if (onLoad) {
  9259. texture.onLoadedCallbacks.push(onLoad);
  9260. }
  9261. if (!fallBack)
  9262. this._loadedTexturesCache.push(texture);
  9263. var onerror = function () {
  9264. scene._removePendingData(texture);
  9265. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9266. if (isKTX) {
  9267. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9268. }
  9269. else if (onError) {
  9270. onError();
  9271. }
  9272. };
  9273. var callback;
  9274. // processing for non-image formats
  9275. if (isKTX || isTGA || isDDS) {
  9276. if (isKTX) {
  9277. callback = function (data) {
  9278. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9279. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9280. ktx.uploadLevels(_this._gl, !noMipmap);
  9281. }, samplingMode);
  9282. };
  9283. }
  9284. else if (isTGA) {
  9285. callback = function (arrayBuffer) {
  9286. var data = new Uint8Array(arrayBuffer);
  9287. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9288. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9289. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9290. }, samplingMode);
  9291. };
  9292. }
  9293. else if (isDDS) {
  9294. callback = function (data) {
  9295. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9296. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9297. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9298. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 1);
  9299. }, samplingMode);
  9300. };
  9301. }
  9302. if (!buffer) {
  9303. BABYLON.Tools.LoadFile(url, function (data) {
  9304. callback(data);
  9305. }, null, scene.database, true, onerror);
  9306. }
  9307. else {
  9308. callback(buffer);
  9309. }
  9310. // image format processing
  9311. }
  9312. else {
  9313. var onload = function (img) {
  9314. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9315. var isPot = (img.width === potWidth && img.height === potHeight);
  9316. if (!isPot) {
  9317. _this._prepareWorkingCanvas();
  9318. _this._workingCanvas.width = potWidth;
  9319. _this._workingCanvas.height = potHeight;
  9320. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9321. _this._workingContext.imageSmoothingEnabled = false;
  9322. _this._workingContext.mozImageSmoothingEnabled = false;
  9323. _this._workingContext.oImageSmoothingEnabled = false;
  9324. _this._workingContext.webkitImageSmoothingEnabled = false;
  9325. _this._workingContext.msImageSmoothingEnabled = false;
  9326. }
  9327. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9328. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9329. _this._workingContext.imageSmoothingEnabled = true;
  9330. _this._workingContext.mozImageSmoothingEnabled = true;
  9331. _this._workingContext.oImageSmoothingEnabled = true;
  9332. _this._workingContext.webkitImageSmoothingEnabled = true;
  9333. _this._workingContext.msImageSmoothingEnabled = true;
  9334. }
  9335. }
  9336. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9337. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9338. }, samplingMode);
  9339. };
  9340. if (!fromData || isBase64)
  9341. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9342. else if (buffer instanceof Array || typeof buffer === "string")
  9343. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9344. else
  9345. onload(buffer);
  9346. }
  9347. return texture;
  9348. };
  9349. Engine.prototype._getInternalFormat = function (format) {
  9350. var internalFormat = this._gl.RGBA;
  9351. switch (format) {
  9352. case Engine.TEXTUREFORMAT_ALPHA:
  9353. internalFormat = this._gl.ALPHA;
  9354. break;
  9355. case Engine.TEXTUREFORMAT_LUMINANCE:
  9356. internalFormat = this._gl.LUMINANCE;
  9357. break;
  9358. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9359. internalFormat = this._gl.LUMINANCE_ALPHA;
  9360. break;
  9361. case Engine.TEXTUREFORMAT_RGB:
  9362. internalFormat = this._gl.RGB;
  9363. break;
  9364. case Engine.TEXTUREFORMAT_RGBA:
  9365. internalFormat = this._gl.RGBA;
  9366. break;
  9367. }
  9368. return internalFormat;
  9369. };
  9370. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9371. if (compression === void 0) { compression = null; }
  9372. var internalFormat = this._getInternalFormat(format);
  9373. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9374. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9375. if (texture._width % 4 !== 0) {
  9376. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9377. }
  9378. if (compression) {
  9379. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9380. }
  9381. else {
  9382. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9383. }
  9384. if (texture.generateMipMaps) {
  9385. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9386. }
  9387. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9388. this.resetTextureCache();
  9389. texture.isReady = true;
  9390. };
  9391. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9392. if (compression === void 0) { compression = null; }
  9393. var texture = this._gl.createTexture();
  9394. texture._baseWidth = width;
  9395. texture._baseHeight = height;
  9396. texture._width = width;
  9397. texture._height = height;
  9398. texture.references = 1;
  9399. this.updateRawTexture(texture, data, format, invertY, compression);
  9400. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9401. // Filters
  9402. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9403. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9404. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9405. if (generateMipMaps) {
  9406. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9407. }
  9408. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9409. texture.samplingMode = samplingMode;
  9410. this._loadedTexturesCache.push(texture);
  9411. return texture;
  9412. };
  9413. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9414. var texture = this._gl.createTexture();
  9415. texture._baseWidth = width;
  9416. texture._baseHeight = height;
  9417. if (generateMipMaps) {
  9418. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9419. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9420. }
  9421. this.resetTextureCache();
  9422. texture._width = width;
  9423. texture._height = height;
  9424. texture.isReady = false;
  9425. texture.generateMipMaps = generateMipMaps;
  9426. texture.references = 1;
  9427. texture.samplingMode = samplingMode;
  9428. this.updateTextureSamplingMode(samplingMode, texture);
  9429. this._loadedTexturesCache.push(texture);
  9430. return texture;
  9431. };
  9432. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9433. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9434. if (texture.isCube) {
  9435. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9436. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9437. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9438. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9439. }
  9440. else {
  9441. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9442. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9443. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9444. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9445. }
  9446. texture.samplingMode = samplingMode;
  9447. };
  9448. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9449. if (premulAlpha === void 0) { premulAlpha = false; }
  9450. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9451. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9452. if (premulAlpha) {
  9453. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9454. }
  9455. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9456. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9457. if (texture.generateMipMaps) {
  9458. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9459. }
  9460. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9461. if (premulAlpha) {
  9462. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9463. }
  9464. this.resetTextureCache();
  9465. texture.isReady = true;
  9466. };
  9467. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9468. if (texture._isDisabled) {
  9469. return;
  9470. }
  9471. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9472. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9473. try {
  9474. // Testing video texture support
  9475. if (this._videoTextureSupported === undefined) {
  9476. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9477. if (this._gl.getError() !== 0) {
  9478. this._videoTextureSupported = false;
  9479. }
  9480. else {
  9481. this._videoTextureSupported = true;
  9482. }
  9483. }
  9484. // Copy video through the current working canvas if video texture is not supported
  9485. if (!this._videoTextureSupported) {
  9486. if (!texture._workingCanvas) {
  9487. texture._workingCanvas = document.createElement("canvas");
  9488. texture._workingContext = texture._workingCanvas.getContext("2d");
  9489. texture._workingCanvas.width = texture._width;
  9490. texture._workingCanvas.height = texture._height;
  9491. }
  9492. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9493. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9494. }
  9495. else {
  9496. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9497. }
  9498. if (texture.generateMipMaps) {
  9499. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9500. }
  9501. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9502. this.resetTextureCache();
  9503. texture.isReady = true;
  9504. }
  9505. catch (ex) {
  9506. // Something unexpected
  9507. // Let's disable the texture
  9508. texture._isDisabled = true;
  9509. }
  9510. };
  9511. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9512. // old version had a "generateMipMaps" arg instead of options.
  9513. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9514. // in the same way, generateDepthBuffer is defaulted to true
  9515. var generateMipMaps = false;
  9516. var generateDepthBuffer = true;
  9517. var generateStencilBuffer = false;
  9518. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9519. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9520. if (options !== undefined) {
  9521. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9522. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9523. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9524. type = options.type === undefined ? type : options.type;
  9525. if (options.samplingMode !== undefined) {
  9526. samplingMode = options.samplingMode;
  9527. }
  9528. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9529. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9530. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9531. }
  9532. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9533. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9534. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9535. }
  9536. }
  9537. var gl = this._gl;
  9538. var texture = gl.createTexture();
  9539. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9540. var width = size.width || size;
  9541. var height = size.height || size;
  9542. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9543. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9544. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9545. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9546. }
  9547. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9548. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9549. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9550. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9551. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9552. // Create the framebuffer
  9553. var framebuffer = gl.createFramebuffer();
  9554. this.bindUnboundFramebuffer(framebuffer);
  9555. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9556. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9557. if (generateMipMaps) {
  9558. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9559. }
  9560. // Unbind
  9561. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9562. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9563. this.bindUnboundFramebuffer(null);
  9564. texture._framebuffer = framebuffer;
  9565. texture._baseWidth = width;
  9566. texture._baseHeight = height;
  9567. texture._width = width;
  9568. texture._height = height;
  9569. texture.isReady = true;
  9570. texture.samples = 1;
  9571. texture.generateMipMaps = generateMipMaps;
  9572. texture.references = 1;
  9573. texture.samplingMode = samplingMode;
  9574. texture.type = type;
  9575. texture._generateDepthBuffer = generateDepthBuffer;
  9576. texture._generateStencilBuffer = generateStencilBuffer;
  9577. this.resetTextureCache();
  9578. this._loadedTexturesCache.push(texture);
  9579. return texture;
  9580. };
  9581. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9582. var generateMipMaps = false;
  9583. var generateDepthBuffer = true;
  9584. var generateStencilBuffer = false;
  9585. var generateDepthTexture = false;
  9586. var textureCount = 1;
  9587. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9588. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9589. var types = [], samplingModes = [];
  9590. if (options !== undefined) {
  9591. generateMipMaps = options.generateMipMaps;
  9592. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9593. generateStencilBuffer = options.generateStencilBuffer;
  9594. generateDepthTexture = options.generateDepthTexture;
  9595. textureCount = options.textureCount || 1;
  9596. if (options.types) {
  9597. types = options.types;
  9598. }
  9599. if (options.samplingModes) {
  9600. samplingModes = options.samplingModes;
  9601. }
  9602. }
  9603. var gl = this._gl;
  9604. // Create the framebuffer
  9605. var framebuffer = gl.createFramebuffer();
  9606. this.bindUnboundFramebuffer(framebuffer);
  9607. var width = size.width || size;
  9608. var height = size.height || size;
  9609. var textures = [];
  9610. var attachments = [];
  9611. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9612. for (var i = 0; i < textureCount; i++) {
  9613. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9614. var type = types[i] || defaultType;
  9615. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9616. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9617. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9618. }
  9619. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9620. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9621. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9622. }
  9623. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9624. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9625. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9626. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9627. }
  9628. var texture = gl.createTexture();
  9629. var attachment = gl["COLOR_ATTACHMENT" + i];
  9630. textures.push(texture);
  9631. attachments.push(attachment);
  9632. gl.activeTexture(gl["TEXTURE" + i]);
  9633. gl.bindTexture(gl.TEXTURE_2D, texture);
  9634. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9635. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9637. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9638. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9639. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9640. if (generateMipMaps) {
  9641. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9642. }
  9643. // Unbind
  9644. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9645. texture._framebuffer = framebuffer;
  9646. texture._depthStencilBuffer = depthStencilBuffer;
  9647. texture._baseWidth = width;
  9648. texture._baseHeight = height;
  9649. texture._width = width;
  9650. texture._height = height;
  9651. texture.isReady = true;
  9652. texture.samples = 1;
  9653. texture.generateMipMaps = generateMipMaps;
  9654. texture.references = 1;
  9655. texture.samplingMode = samplingMode;
  9656. texture.type = type;
  9657. texture._generateDepthBuffer = generateDepthBuffer;
  9658. texture._generateStencilBuffer = generateStencilBuffer;
  9659. this._loadedTexturesCache.push(texture);
  9660. }
  9661. if (generateDepthTexture) {
  9662. // Depth texture
  9663. var depthTexture = gl.createTexture();
  9664. gl.activeTexture(gl.TEXTURE0);
  9665. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9666. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9667. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9668. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9669. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9670. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9671. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9672. depthTexture._framebuffer = framebuffer;
  9673. depthTexture._baseWidth = width;
  9674. depthTexture._baseHeight = height;
  9675. depthTexture._width = width;
  9676. depthTexture._height = height;
  9677. depthTexture.isReady = true;
  9678. depthTexture.samples = 1;
  9679. depthTexture.generateMipMaps = generateMipMaps;
  9680. depthTexture.references = 1;
  9681. depthTexture.samplingMode = gl.NEAREST;
  9682. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9683. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9684. textures.push(depthTexture);
  9685. this._loadedTexturesCache.push(depthTexture);
  9686. }
  9687. gl.drawBuffers(attachments);
  9688. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9689. this.bindUnboundFramebuffer(null);
  9690. this.resetTextureCache();
  9691. return textures;
  9692. };
  9693. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9694. if (samples === void 0) { samples = 1; }
  9695. var depthStencilBuffer = null;
  9696. var gl = this._gl;
  9697. // Create the depth/stencil buffer
  9698. if (generateStencilBuffer) {
  9699. depthStencilBuffer = gl.createRenderbuffer();
  9700. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9701. if (samples > 1) {
  9702. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  9703. }
  9704. else {
  9705. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9706. }
  9707. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9708. }
  9709. else if (generateDepthBuffer) {
  9710. depthStencilBuffer = gl.createRenderbuffer();
  9711. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9712. if (samples > 1) {
  9713. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9714. }
  9715. else {
  9716. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9717. }
  9718. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9719. }
  9720. return depthStencilBuffer;
  9721. };
  9722. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9723. if (this.webGLVersion < 2) {
  9724. return 1;
  9725. }
  9726. if (texture.samples === samples) {
  9727. return samples;
  9728. }
  9729. var gl = this._gl;
  9730. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9731. // Dispose previous render buffers
  9732. if (texture._depthStencilBuffer) {
  9733. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9734. }
  9735. if (texture._MSAAFramebuffer) {
  9736. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9737. }
  9738. if (texture._MSAARenderBuffer) {
  9739. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9740. }
  9741. if (samples > 1) {
  9742. texture._MSAAFramebuffer = gl.createFramebuffer();
  9743. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9744. var colorRenderbuffer = gl.createRenderbuffer();
  9745. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9746. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9747. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9748. texture._MSAARenderBuffer = colorRenderbuffer;
  9749. }
  9750. else {
  9751. this.bindUnboundFramebuffer(texture._framebuffer);
  9752. }
  9753. texture.samples = samples;
  9754. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9755. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9756. this.bindUnboundFramebuffer(null);
  9757. return samples;
  9758. };
  9759. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  9760. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  9761. };
  9762. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  9763. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  9764. };
  9765. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9766. var gl = this._gl;
  9767. var texture = gl.createTexture();
  9768. var generateMipMaps = true;
  9769. var generateDepthBuffer = true;
  9770. var generateStencilBuffer = false;
  9771. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9772. if (options !== undefined) {
  9773. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9774. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9775. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9776. if (options.samplingMode !== undefined) {
  9777. samplingMode = options.samplingMode;
  9778. }
  9779. }
  9780. texture.isCube = true;
  9781. texture.references = 1;
  9782. texture.generateMipMaps = generateMipMaps;
  9783. texture.references = 1;
  9784. texture.samples = 1;
  9785. texture.samplingMode = samplingMode;
  9786. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9787. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9788. for (var face = 0; face < 6; face++) {
  9789. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9790. }
  9791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9793. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9795. // Create the framebuffer
  9796. var framebuffer = gl.createFramebuffer();
  9797. this.bindUnboundFramebuffer(framebuffer);
  9798. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9799. // Mipmaps
  9800. if (texture.generateMipMaps) {
  9801. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9802. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9803. }
  9804. // Unbind
  9805. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9806. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9807. this.bindUnboundFramebuffer(null);
  9808. texture._framebuffer = framebuffer;
  9809. texture._width = size;
  9810. texture._height = size;
  9811. texture.isReady = true;
  9812. this.resetTextureCache();
  9813. this._loadedTexturesCache.push(texture);
  9814. return texture;
  9815. };
  9816. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format) {
  9817. var _this = this;
  9818. if (onError === void 0) { onError = null; }
  9819. var callback = function (loadData) {
  9820. if (_this._caps.textureLOD || !loadData) {
  9821. // Do not add extra process if texture lod is supported.
  9822. if (onLoad) {
  9823. onLoad();
  9824. }
  9825. return;
  9826. }
  9827. var mipSlices = 3;
  9828. var gl = _this._gl;
  9829. var width = loadData.width;
  9830. if (!width) {
  9831. return;
  9832. }
  9833. var textures = [];
  9834. for (var i = 0; i < mipSlices; i++) {
  9835. //compute LOD from even spacing in smoothness (matching shader calculation)
  9836. var smoothness = i / (mipSlices - 1);
  9837. var roughness = 1 - smoothness;
  9838. var minLODIndex = offset; // roughness = 0
  9839. var maxLODIndex = BABYLON.MathTools.Log2(width) * scale + offset; // roughness = 1
  9840. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  9841. var mipmapIndex = Math.min(Math.max(Math.round(lodIndex), 0), maxLODIndex);
  9842. var glTextureFromLod = gl.createTexture();
  9843. glTextureFromLod.isCube = true;
  9844. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  9845. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9846. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9847. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9849. if (loadData.isDDS) {
  9850. var info = loadData.info;
  9851. var data = loadData.data;
  9852. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  9853. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, true, 6, mipmapIndex);
  9854. }
  9855. else {
  9856. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  9857. }
  9858. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9859. // Wrap in a base texture for easy binding.
  9860. var lodTexture = new BABYLON.BaseTexture(scene);
  9861. lodTexture.isCube = true;
  9862. lodTexture._texture = glTextureFromLod;
  9863. glTextureFromLod.isReady = true;
  9864. textures.push(lodTexture);
  9865. }
  9866. loadData.texture._lodTextureHigh = textures[2];
  9867. loadData.texture._lodTextureMid = textures[1];
  9868. loadData.texture._lodTextureLow = textures[0];
  9869. if (onLoad) {
  9870. onLoad();
  9871. }
  9872. };
  9873. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format);
  9874. };
  9875. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9876. var _this = this;
  9877. if (onLoad === void 0) { onLoad = null; }
  9878. if (onError === void 0) { onError = null; }
  9879. var gl = this._gl;
  9880. var texture = gl.createTexture();
  9881. texture.isCube = true;
  9882. texture.url = rootUrl;
  9883. texture.references = 1;
  9884. texture.onLoadedCallbacks = [];
  9885. texture.generateMipMaps = !noMipmap;
  9886. var isKTX = false;
  9887. var isDDS = false;
  9888. var lastDot = rootUrl.lastIndexOf('.');
  9889. var extension = rootUrl.substring(lastDot).toLowerCase();
  9890. if (this._textureFormatInUse) {
  9891. extension = this._textureFormatInUse;
  9892. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9893. isKTX = true;
  9894. }
  9895. else {
  9896. isDDS = (extension === ".dds");
  9897. }
  9898. if (isKTX) {
  9899. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9900. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9901. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9902. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9903. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9904. ktx.uploadLevels(_this._gl, !noMipmap);
  9905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9909. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9910. _this.resetTextureCache();
  9911. texture._width = ktx.pixelWidth;
  9912. texture._height = ktx.pixelHeight;
  9913. texture.isReady = true;
  9914. }, null, null, true, onError);
  9915. }
  9916. else if (isDDS) {
  9917. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9918. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9919. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9920. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9921. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  9922. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 6);
  9923. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9924. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9925. }
  9926. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9930. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9931. _this.resetTextureCache();
  9932. texture._width = info.width;
  9933. texture._height = info.height;
  9934. texture.isReady = true;
  9935. texture.type = info.textureType;
  9936. if (onLoad) {
  9937. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  9938. }
  9939. }, null, null, true, onError);
  9940. }
  9941. else {
  9942. cascadeLoad(rootUrl, scene, function (imgs) {
  9943. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  9944. var height = width;
  9945. _this._prepareWorkingCanvas();
  9946. _this._workingCanvas.width = width;
  9947. _this._workingCanvas.height = height;
  9948. var faces = [
  9949. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9950. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9951. ];
  9952. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9953. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9954. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9955. for (var index = 0; index < faces.length; index++) {
  9956. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9957. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9958. }
  9959. if (!noMipmap) {
  9960. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9961. }
  9962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9965. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9966. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9967. _this.resetTextureCache();
  9968. texture._width = width;
  9969. texture._height = height;
  9970. texture.isReady = true;
  9971. texture.onLoadedCallbacks.forEach(function (callback) {
  9972. callback();
  9973. });
  9974. if (onLoad) {
  9975. onLoad();
  9976. }
  9977. }, files, onError);
  9978. }
  9979. this._loadedTexturesCache.push(texture);
  9980. return texture;
  9981. };
  9982. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9983. texture._width = width;
  9984. texture._height = height;
  9985. texture._size = width * height;
  9986. texture._baseWidth = width;
  9987. texture._baseHeight = height;
  9988. };
  9989. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9990. if (compression === void 0) { compression = null; }
  9991. if (level === void 0) { level = 0; }
  9992. var gl = this._gl;
  9993. var textureType = this._getWebGLTextureType(type);
  9994. var internalFormat = this._getInternalFormat(format);
  9995. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9996. var needConversion = false;
  9997. if (internalFormat === gl.RGB) {
  9998. internalFormat = gl.RGBA;
  9999. needConversion = true;
  10000. }
  10001. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10002. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10003. if (texture._width % 4 !== 0) {
  10004. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10005. }
  10006. // Data are known to be in +X +Y +Z -X -Y -Z
  10007. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10008. var faceData = data[faceIndex];
  10009. if (compression) {
  10010. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  10011. }
  10012. else {
  10013. if (needConversion) {
  10014. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  10015. }
  10016. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  10017. }
  10018. }
  10019. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  10020. if (isPot && texture.generateMipMaps && level === 0) {
  10021. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10022. }
  10023. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10024. this.resetTextureCache();
  10025. texture.isReady = true;
  10026. };
  10027. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10028. if (compression === void 0) { compression = null; }
  10029. var gl = this._gl;
  10030. var texture = gl.createTexture();
  10031. texture.isCube = true;
  10032. texture.references = 1;
  10033. texture.generateMipMaps = generateMipMaps;
  10034. texture.format = format;
  10035. texture.type = type;
  10036. var textureType = this._getWebGLTextureType(type);
  10037. var internalFormat = this._getInternalFormat(format);
  10038. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10039. var needConversion = false;
  10040. if (internalFormat === gl.RGB) {
  10041. internalFormat = gl.RGBA;
  10042. needConversion = true;
  10043. }
  10044. var width = size;
  10045. var height = width;
  10046. texture._width = width;
  10047. texture._height = height;
  10048. // Double check on POT to generate Mips.
  10049. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  10050. if (!isPot) {
  10051. generateMipMaps = false;
  10052. }
  10053. // Upload data if needed. The texture won t be ready until then.
  10054. if (data) {
  10055. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10056. }
  10057. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10058. // Filters
  10059. if (data && generateMipMaps) {
  10060. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10061. }
  10062. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10063. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10065. }
  10066. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10069. }
  10070. else {
  10071. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10073. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10074. }
  10075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10076. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10077. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10078. return texture;
  10079. };
  10080. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10081. var _this = this;
  10082. if (onLoad === void 0) { onLoad = null; }
  10083. if (onError === void 0) { onError = null; }
  10084. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10085. if (invertY === void 0) { invertY = false; }
  10086. var gl = this._gl;
  10087. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10088. scene._addPendingData(texture);
  10089. texture.url = url;
  10090. this._loadedTexturesCache.push(texture);
  10091. var onerror = function () {
  10092. scene._removePendingData(texture);
  10093. if (onError) {
  10094. onError();
  10095. }
  10096. };
  10097. var internalCallback = function (data) {
  10098. var width = texture._width;
  10099. var height = texture._height;
  10100. var faceDataArrays = callback(data);
  10101. if (mipmmapGenerator) {
  10102. var textureType = _this._getWebGLTextureType(type);
  10103. var internalFormat = _this._getInternalFormat(format);
  10104. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10105. var needConversion = false;
  10106. if (internalFormat === gl.RGB) {
  10107. internalFormat = gl.RGBA;
  10108. needConversion = true;
  10109. }
  10110. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10111. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10112. var mipData = mipmmapGenerator(faceDataArrays);
  10113. for (var level = 0; level < mipData.length; level++) {
  10114. var mipSize = width >> level;
  10115. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10116. var mipFaceData = mipData[level][faceIndex];
  10117. if (needConversion) {
  10118. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10119. }
  10120. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10121. }
  10122. }
  10123. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10124. }
  10125. else {
  10126. texture.generateMipMaps = !noMipmap;
  10127. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10128. }
  10129. texture.isReady = true;
  10130. _this.resetTextureCache();
  10131. scene._removePendingData(texture);
  10132. if (onLoad) {
  10133. onLoad();
  10134. }
  10135. };
  10136. BABYLON.Tools.LoadFile(url, function (data) {
  10137. internalCallback(data);
  10138. }, onerror, scene.database, true);
  10139. return texture;
  10140. };
  10141. ;
  10142. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10143. // Create new RGBA data container.
  10144. var rgbaData;
  10145. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10146. rgbaData = new Float32Array(width * height * 4);
  10147. }
  10148. else {
  10149. rgbaData = new Uint32Array(width * height * 4);
  10150. }
  10151. // Convert each pixel.
  10152. for (var x = 0; x < width; x++) {
  10153. for (var y = 0; y < height; y++) {
  10154. var index = (y * width + x) * 3;
  10155. var newIndex = (y * width + x) * 4;
  10156. // Map Old Value to new value.
  10157. rgbaData[newIndex + 0] = rgbData[index + 0];
  10158. rgbaData[newIndex + 1] = rgbData[index + 1];
  10159. rgbaData[newIndex + 2] = rgbData[index + 2];
  10160. // Add fully opaque alpha channel.
  10161. rgbaData[newIndex + 3] = 1;
  10162. }
  10163. }
  10164. return rgbaData;
  10165. };
  10166. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10167. var gl = this._gl;
  10168. if (texture._framebuffer) {
  10169. gl.deleteFramebuffer(texture._framebuffer);
  10170. texture._framebuffer = null;
  10171. }
  10172. if (texture._depthStencilBuffer) {
  10173. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10174. texture._depthStencilBuffer = null;
  10175. }
  10176. if (texture._MSAAFramebuffer) {
  10177. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10178. texture._MSAAFramebuffer = null;
  10179. }
  10180. if (texture._MSAARenderBuffer) {
  10181. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10182. texture._MSAARenderBuffer = null;
  10183. }
  10184. };
  10185. Engine.prototype._releaseTexture = function (texture) {
  10186. var gl = this._gl;
  10187. this._releaseFramebufferObjects(texture);
  10188. gl.deleteTexture(texture);
  10189. // Unbind channels
  10190. this.unbindAllTextures();
  10191. var index = this._loadedTexturesCache.indexOf(texture);
  10192. if (index !== -1) {
  10193. this._loadedTexturesCache.splice(index, 1);
  10194. }
  10195. // Integrated fixed lod samplers.
  10196. if (texture._lodTextureHigh) {
  10197. texture._lodTextureHigh.dispose();
  10198. }
  10199. if (texture._lodTextureMid) {
  10200. texture._lodTextureMid.dispose();
  10201. }
  10202. if (texture._lodTextureLow) {
  10203. texture._lodTextureLow.dispose();
  10204. }
  10205. };
  10206. Engine.prototype.setProgram = function (program) {
  10207. if (this._currentProgram !== program) {
  10208. this._gl.useProgram(program);
  10209. this._currentProgram = program;
  10210. }
  10211. };
  10212. Engine.prototype.bindSamplers = function (effect) {
  10213. this.setProgram(effect.getProgram());
  10214. var samplers = effect.getSamplers();
  10215. for (var index = 0; index < samplers.length; index++) {
  10216. var uniform = effect.getUniform(samplers[index]);
  10217. this._gl.uniform1i(uniform, index);
  10218. }
  10219. this._currentEffect = null;
  10220. };
  10221. Engine.prototype.activateTexture = function (texture) {
  10222. if (this._activeTexture !== texture) {
  10223. this._gl.activeTexture(texture);
  10224. this._activeTexture = texture;
  10225. }
  10226. };
  10227. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10228. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10229. this._gl.bindTexture(target, texture);
  10230. this._activeTexturesCache[this._activeTexture] = texture;
  10231. }
  10232. };
  10233. Engine.prototype._bindTexture = function (channel, texture) {
  10234. if (channel < 0) {
  10235. return;
  10236. }
  10237. this.activateTexture(this._gl.TEXTURE0 + channel);
  10238. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10239. };
  10240. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10241. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10242. };
  10243. Engine.prototype.unbindAllTextures = function () {
  10244. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10245. this.activateTexture(this._gl["TEXTURE" + channel]);
  10246. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10247. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10248. }
  10249. };
  10250. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10251. if (channel < 0) {
  10252. return;
  10253. }
  10254. this._gl.uniform1i(uniform, channel);
  10255. this._setTexture(channel, texture);
  10256. };
  10257. Engine.prototype._setTexture = function (channel, texture) {
  10258. // Not ready?
  10259. if (!texture) {
  10260. if (this._activeTexturesCache[channel] != null) {
  10261. this.activateTexture(this._gl["TEXTURE" + channel]);
  10262. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10263. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10264. }
  10265. return;
  10266. }
  10267. // Video
  10268. var alreadyActivated = false;
  10269. if (texture.video) {
  10270. this.activateTexture(this._gl["TEXTURE" + channel]);
  10271. alreadyActivated = true;
  10272. texture.update();
  10273. }
  10274. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10275. texture.delayLoad();
  10276. return;
  10277. }
  10278. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10279. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10280. if (this._activeTexturesCache[channel] === internalTexture) {
  10281. return;
  10282. }
  10283. if (!alreadyActivated) {
  10284. this.activateTexture(this._gl["TEXTURE" + channel]);
  10285. }
  10286. if (internalTexture.isCube) {
  10287. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10288. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10289. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10290. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10291. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10292. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10293. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10294. }
  10295. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10296. }
  10297. else {
  10298. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10299. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10300. internalTexture._cachedWrapU = texture.wrapU;
  10301. switch (texture.wrapU) {
  10302. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10303. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10304. break;
  10305. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10306. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10307. break;
  10308. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10309. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10310. break;
  10311. }
  10312. }
  10313. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10314. internalTexture._cachedWrapV = texture.wrapV;
  10315. switch (texture.wrapV) {
  10316. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10317. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10318. break;
  10319. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10321. break;
  10322. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10324. break;
  10325. }
  10326. }
  10327. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10328. }
  10329. };
  10330. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10331. if (channel < 0) {
  10332. return;
  10333. }
  10334. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10335. this._textureUnits = new Int32Array(textures.length);
  10336. }
  10337. for (var i = 0; i < textures.length; i++) {
  10338. this._textureUnits[i] = channel + i;
  10339. }
  10340. this._gl.uniform1iv(uniform, this._textureUnits);
  10341. for (var index = 0; index < textures.length; index++) {
  10342. this._setTexture(channel + index, textures[index]);
  10343. }
  10344. };
  10345. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10346. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10347. var value = texture.anisotropicFilteringLevel;
  10348. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10349. value = 1;
  10350. }
  10351. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10352. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10353. texture._cachedAnisotropicFilteringLevel = value;
  10354. }
  10355. };
  10356. Engine.prototype.readPixels = function (x, y, width, height) {
  10357. var data = new Uint8Array(height * width * 4);
  10358. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10359. return data;
  10360. };
  10361. /**
  10362. * Add an externaly attached data from its key.
  10363. * This method call will fail and return false, if such key already exists.
  10364. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10365. * @param key the unique key that identifies the data
  10366. * @param data the data object to associate to the key for this Engine instance
  10367. * @return true if no such key were already present and the data was added successfully, false otherwise
  10368. */
  10369. Engine.prototype.addExternalData = function (key, data) {
  10370. if (!this._externalData) {
  10371. this._externalData = new BABYLON.StringDictionary();
  10372. }
  10373. return this._externalData.add(key, data);
  10374. };
  10375. /**
  10376. * Get an externaly attached data from its key
  10377. * @param key the unique key that identifies the data
  10378. * @return the associated data, if present (can be null), or undefined if not present
  10379. */
  10380. Engine.prototype.getExternalData = function (key) {
  10381. if (!this._externalData) {
  10382. this._externalData = new BABYLON.StringDictionary();
  10383. }
  10384. return this._externalData.get(key);
  10385. };
  10386. /**
  10387. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10388. * @param key the unique key that identifies the data
  10389. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10390. * @return the associated data, can be null if the factory returned null.
  10391. */
  10392. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10393. if (!this._externalData) {
  10394. this._externalData = new BABYLON.StringDictionary();
  10395. }
  10396. return this._externalData.getOrAddWithFactory(key, factory);
  10397. };
  10398. /**
  10399. * Remove an externaly attached data from the Engine instance
  10400. * @param key the unique key that identifies the data
  10401. * @return true if the data was successfully removed, false if it doesn't exist
  10402. */
  10403. Engine.prototype.removeExternalData = function (key) {
  10404. if (!this._externalData) {
  10405. this._externalData = new BABYLON.StringDictionary();
  10406. }
  10407. return this._externalData.remove(key);
  10408. };
  10409. Engine.prototype.releaseInternalTexture = function (texture) {
  10410. if (!texture) {
  10411. return;
  10412. }
  10413. texture.references--;
  10414. // Final reference ?
  10415. if (texture.references === 0) {
  10416. var texturesCache = this.getLoadedTexturesCache();
  10417. var index = texturesCache.indexOf(texture);
  10418. if (index > -1) {
  10419. texturesCache.splice(index, 1);
  10420. }
  10421. this._releaseTexture(texture);
  10422. }
  10423. };
  10424. Engine.prototype.unbindAllAttributes = function () {
  10425. if (this._mustWipeVertexAttributes) {
  10426. this._mustWipeVertexAttributes = false;
  10427. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10428. this._gl.disableVertexAttribArray(i);
  10429. this._vertexAttribArraysEnabled[i] = false;
  10430. this._currentBufferPointers[i].active = false;
  10431. }
  10432. return;
  10433. }
  10434. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10435. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10436. continue;
  10437. }
  10438. this._gl.disableVertexAttribArray(i);
  10439. this._vertexAttribArraysEnabled[i] = false;
  10440. this._currentBufferPointers[i].active = false;
  10441. }
  10442. };
  10443. Engine.prototype.releaseEffects = function () {
  10444. for (var name in this._compiledEffects) {
  10445. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10446. }
  10447. this._compiledEffects = {};
  10448. };
  10449. // Dispose
  10450. Engine.prototype.dispose = function () {
  10451. this.hideLoadingUI();
  10452. this.stopRenderLoop();
  10453. // Empty texture
  10454. if (this._emptyTexture) {
  10455. this._releaseTexture(this._emptyTexture);
  10456. this._emptyTexture = null;
  10457. }
  10458. if (this._emptyCubeTexture) {
  10459. this._releaseTexture(this._emptyCubeTexture);
  10460. this._emptyCubeTexture = null;
  10461. }
  10462. // Release scenes
  10463. while (this.scenes.length) {
  10464. this.scenes[0].dispose();
  10465. }
  10466. // Release audio engine
  10467. if (Engine.audioEngine) {
  10468. Engine.audioEngine.dispose();
  10469. }
  10470. // Release effects
  10471. this.releaseEffects();
  10472. // Unbind
  10473. this.unbindAllAttributes();
  10474. if (this._dummyFramebuffer) {
  10475. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10476. }
  10477. this._gl = null;
  10478. //WebVR
  10479. this.disableVR();
  10480. // Events
  10481. window.removeEventListener("blur", this._onBlur);
  10482. window.removeEventListener("focus", this._onFocus);
  10483. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10484. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10485. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10486. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10487. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10488. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10489. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10490. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10491. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10492. // Remove from Instances
  10493. var index = Engine.Instances.indexOf(this);
  10494. if (index >= 0) {
  10495. Engine.Instances.splice(index, 1);
  10496. }
  10497. };
  10498. // Loading screen
  10499. Engine.prototype.displayLoadingUI = function () {
  10500. var loadingScreen = this.loadingScreen;
  10501. if (loadingScreen) {
  10502. loadingScreen.displayLoadingUI();
  10503. }
  10504. };
  10505. Engine.prototype.hideLoadingUI = function () {
  10506. var loadingScreen = this.loadingScreen;
  10507. if (loadingScreen) {
  10508. loadingScreen.hideLoadingUI();
  10509. }
  10510. };
  10511. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10512. get: function () {
  10513. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10514. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10515. return this._loadingScreen;
  10516. },
  10517. set: function (loadingScreen) {
  10518. this._loadingScreen = loadingScreen;
  10519. },
  10520. enumerable: true,
  10521. configurable: true
  10522. });
  10523. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10524. set: function (text) {
  10525. this.loadingScreen.loadingUIText = text;
  10526. },
  10527. enumerable: true,
  10528. configurable: true
  10529. });
  10530. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10531. set: function (color) {
  10532. this.loadingScreen.loadingUIBackgroundColor = color;
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. Engine.prototype.attachContextLostEvent = function (callback) {
  10538. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10539. };
  10540. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10541. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10542. };
  10543. Engine.prototype.getVertexShaderSource = function (program) {
  10544. var shaders = this._gl.getAttachedShaders(program);
  10545. return this._gl.getShaderSource(shaders[0]);
  10546. };
  10547. Engine.prototype.getFragmentShaderSource = function (program) {
  10548. var shaders = this._gl.getAttachedShaders(program);
  10549. return this._gl.getShaderSource(shaders[1]);
  10550. };
  10551. Engine.prototype.getError = function () {
  10552. return this._gl.getError();
  10553. };
  10554. // FPS
  10555. Engine.prototype.getFps = function () {
  10556. return this._fps;
  10557. };
  10558. Engine.prototype.getDeltaTime = function () {
  10559. return this._deltaTime;
  10560. };
  10561. Engine.prototype._measureFps = function () {
  10562. this._performanceMonitor.sampleFrame();
  10563. this._fps = this._performanceMonitor.averageFPS;
  10564. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10565. };
  10566. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10567. if (faceIndex === void 0) { faceIndex = -1; }
  10568. var gl = this._gl;
  10569. if (!this._dummyFramebuffer) {
  10570. this._dummyFramebuffer = gl.createFramebuffer();
  10571. }
  10572. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10573. if (faceIndex > -1) {
  10574. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  10575. }
  10576. else {
  10577. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10578. }
  10579. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10580. var buffer;
  10581. switch (readType) {
  10582. case gl.UNSIGNED_BYTE:
  10583. buffer = new Uint8Array(4 * width * height);
  10584. readType = gl.UNSIGNED_BYTE;
  10585. break;
  10586. default:
  10587. buffer = new Float32Array(4 * width * height);
  10588. readType = gl.FLOAT;
  10589. break;
  10590. }
  10591. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  10592. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10593. return buffer;
  10594. };
  10595. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10596. if (this._webGLVersion > 1) {
  10597. return this._caps.colorBufferFloat;
  10598. }
  10599. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10600. };
  10601. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10602. if (this._webGLVersion > 1) {
  10603. return this._caps.colorBufferFloat;
  10604. }
  10605. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10606. };
  10607. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10608. Engine.prototype._canRenderToFramebuffer = function (type) {
  10609. var gl = this._gl;
  10610. //clear existing errors
  10611. while (gl.getError() !== gl.NO_ERROR) { }
  10612. var successful = true;
  10613. var texture = gl.createTexture();
  10614. gl.bindTexture(gl.TEXTURE_2D, texture);
  10615. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10616. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10617. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10618. var fb = gl.createFramebuffer();
  10619. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10620. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10621. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10622. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10623. successful = successful && (gl.getError() === gl.NO_ERROR);
  10624. //try render by clearing frame buffer's color buffer
  10625. if (successful) {
  10626. gl.clear(gl.COLOR_BUFFER_BIT);
  10627. successful = successful && (gl.getError() === gl.NO_ERROR);
  10628. }
  10629. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10630. if (successful) {
  10631. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10632. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10633. var readFormat = gl.RGBA;
  10634. var readType = gl.UNSIGNED_BYTE;
  10635. var buffer = new Uint8Array(4);
  10636. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10637. successful = successful && (gl.getError() === gl.NO_ERROR);
  10638. }
  10639. //clean up
  10640. gl.deleteTexture(texture);
  10641. gl.deleteFramebuffer(fb);
  10642. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10643. //clear accumulated errors
  10644. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10645. return successful;
  10646. };
  10647. Engine.prototype._getWebGLTextureType = function (type) {
  10648. if (type === Engine.TEXTURETYPE_FLOAT) {
  10649. return this._gl.FLOAT;
  10650. }
  10651. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10652. // Add Half Float Constant.
  10653. return this._gl.HALF_FLOAT_OES;
  10654. }
  10655. return this._gl.UNSIGNED_BYTE;
  10656. };
  10657. ;
  10658. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10659. if (this._webGLVersion === 1) {
  10660. return this._gl.RGBA;
  10661. }
  10662. if (type === Engine.TEXTURETYPE_FLOAT) {
  10663. return this._gl.RGBA32F;
  10664. }
  10665. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10666. return this._gl.RGBA16F;
  10667. }
  10668. return this._gl.RGBA;
  10669. };
  10670. ;
  10671. // Statics
  10672. Engine.isSupported = function () {
  10673. try {
  10674. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10675. if (navigator.isCocoonJS) {
  10676. return true;
  10677. }
  10678. var tempcanvas = document.createElement("canvas");
  10679. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10680. return gl != null && !!window.WebGLRenderingContext;
  10681. }
  10682. catch (e) {
  10683. return false;
  10684. }
  10685. };
  10686. return Engine;
  10687. }());
  10688. Engine.Instances = new Array();
  10689. // Const statics
  10690. Engine._ALPHA_DISABLE = 0;
  10691. Engine._ALPHA_ADD = 1;
  10692. Engine._ALPHA_COMBINE = 2;
  10693. Engine._ALPHA_SUBTRACT = 3;
  10694. Engine._ALPHA_MULTIPLY = 4;
  10695. Engine._ALPHA_MAXIMIZED = 5;
  10696. Engine._ALPHA_ONEONE = 6;
  10697. Engine._ALPHA_PREMULTIPLIED = 7;
  10698. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10699. Engine._ALPHA_INTERPOLATE = 9;
  10700. Engine._ALPHA_SCREENMODE = 10;
  10701. Engine._DELAYLOADSTATE_NONE = 0;
  10702. Engine._DELAYLOADSTATE_LOADED = 1;
  10703. Engine._DELAYLOADSTATE_LOADING = 2;
  10704. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10705. Engine._TEXTUREFORMAT_ALPHA = 0;
  10706. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10707. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10708. Engine._TEXTUREFORMAT_RGB = 4;
  10709. Engine._TEXTUREFORMAT_RGBA = 5;
  10710. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10711. Engine._TEXTURETYPE_FLOAT = 1;
  10712. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10713. // Depht or Stencil test Constants.
  10714. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10715. 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.
  10716. 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.
  10717. 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.
  10718. 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.
  10719. 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.
  10720. 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.
  10721. 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.
  10722. // Stencil Actions Constants.
  10723. Engine._KEEP = 0x1E00;
  10724. Engine._REPLACE = 0x1E01;
  10725. Engine._INCR = 0x1E02;
  10726. Engine._DECR = 0x1E03;
  10727. Engine._INVERT = 0x150A;
  10728. Engine._INCR_WRAP = 0x8507;
  10729. Engine._DECR_WRAP = 0x8508;
  10730. // Texture rescaling mode
  10731. Engine._SCALEMODE_FLOOR = 1;
  10732. Engine._SCALEMODE_NEAREST = 2;
  10733. Engine._SCALEMODE_CEILING = 3;
  10734. // Updatable statics so stick with vars here
  10735. Engine.CollisionsEpsilon = 0.001;
  10736. Engine.CodeRepository = "src/";
  10737. Engine.ShadersRepository = "src/Shaders/";
  10738. BABYLON.Engine = Engine;
  10739. })(BABYLON || (BABYLON = {}));
  10740. //# sourceMappingURL=babylon.engine.js.map
  10741. /// <reference path="Tools\babylon.decorators.ts" />
  10742. var BABYLON;
  10743. (function (BABYLON) {
  10744. /**
  10745. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10746. */
  10747. var Node = (function () {
  10748. /**
  10749. * @constructor
  10750. * @param {string} name - the name and id to be given to this node
  10751. * @param {BABYLON.Scene} the scene this node will be added to
  10752. */
  10753. function Node(name, scene) {
  10754. this.state = "";
  10755. this.metadata = null;
  10756. this.doNotSerialize = false;
  10757. this.animations = new Array();
  10758. this._ranges = {};
  10759. this._childrenFlag = -1;
  10760. this._isEnabled = true;
  10761. this._isReady = true;
  10762. this._currentRenderId = -1;
  10763. this._parentRenderId = -1;
  10764. /**
  10765. * An event triggered when the mesh is disposed.
  10766. * @type {BABYLON.Observable}
  10767. */
  10768. this.onDisposeObservable = new BABYLON.Observable();
  10769. this.name = name;
  10770. this.id = name;
  10771. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10772. this._initCache();
  10773. }
  10774. Object.defineProperty(Node.prototype, "parent", {
  10775. get: function () {
  10776. return this._parentNode;
  10777. },
  10778. set: function (parent) {
  10779. if (this._parentNode === parent) {
  10780. return;
  10781. }
  10782. if (this._parentNode) {
  10783. var index = this._parentNode._children.indexOf(this);
  10784. if (index !== -1) {
  10785. this._parentNode._children.splice(index, 1);
  10786. }
  10787. }
  10788. this._parentNode = parent;
  10789. if (this._parentNode) {
  10790. if (!this._parentNode._children) {
  10791. this._parentNode._children = new Array();
  10792. }
  10793. this._parentNode._children.push(this);
  10794. }
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Node.prototype.getClassName = function () {
  10800. return "Node";
  10801. };
  10802. Object.defineProperty(Node.prototype, "onDispose", {
  10803. set: function (callback) {
  10804. if (this._onDisposeObserver) {
  10805. this.onDisposeObservable.remove(this._onDisposeObserver);
  10806. }
  10807. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10808. },
  10809. enumerable: true,
  10810. configurable: true
  10811. });
  10812. Node.prototype.getScene = function () {
  10813. return this._scene;
  10814. };
  10815. Node.prototype.getEngine = function () {
  10816. return this._scene.getEngine();
  10817. };
  10818. // override it in derived class
  10819. Node.prototype.getWorldMatrix = function () {
  10820. return BABYLON.Matrix.Identity();
  10821. };
  10822. // override it in derived class if you add new variables to the cache
  10823. // and call the parent class method
  10824. Node.prototype._initCache = function () {
  10825. this._cache = {};
  10826. this._cache.parent = undefined;
  10827. };
  10828. Node.prototype.updateCache = function (force) {
  10829. if (!force && this.isSynchronized())
  10830. return;
  10831. this._cache.parent = this.parent;
  10832. this._updateCache();
  10833. };
  10834. // override it in derived class if you add new variables to the cache
  10835. // and call the parent class method if !ignoreParentClass
  10836. Node.prototype._updateCache = function (ignoreParentClass) {
  10837. };
  10838. // override it in derived class if you add new variables to the cache
  10839. Node.prototype._isSynchronized = function () {
  10840. return true;
  10841. };
  10842. Node.prototype._markSyncedWithParent = function () {
  10843. this._parentRenderId = this.parent._currentRenderId;
  10844. };
  10845. Node.prototype.isSynchronizedWithParent = function () {
  10846. if (!this.parent) {
  10847. return true;
  10848. }
  10849. if (this._parentRenderId !== this.parent._currentRenderId) {
  10850. return false;
  10851. }
  10852. return this.parent.isSynchronized();
  10853. };
  10854. Node.prototype.isSynchronized = function (updateCache) {
  10855. var check = this.hasNewParent();
  10856. check = check || !this.isSynchronizedWithParent();
  10857. check = check || !this._isSynchronized();
  10858. if (updateCache)
  10859. this.updateCache(true);
  10860. return !check;
  10861. };
  10862. Node.prototype.hasNewParent = function (update) {
  10863. if (this._cache.parent === this.parent)
  10864. return false;
  10865. if (update)
  10866. this._cache.parent = this.parent;
  10867. return true;
  10868. };
  10869. /**
  10870. * Is this node ready to be used/rendered
  10871. * @return {boolean} is it ready
  10872. */
  10873. Node.prototype.isReady = function () {
  10874. return this._isReady;
  10875. };
  10876. /**
  10877. * Is this node enabled.
  10878. * If the node has a parent and is enabled, the parent will be inspected as well.
  10879. * @return {boolean} whether this node (and its parent) is enabled.
  10880. * @see setEnabled
  10881. */
  10882. Node.prototype.isEnabled = function () {
  10883. if (!this._isEnabled) {
  10884. return false;
  10885. }
  10886. if (this.parent) {
  10887. return this.parent.isEnabled();
  10888. }
  10889. return true;
  10890. };
  10891. /**
  10892. * Set the enabled state of this node.
  10893. * @param {boolean} value - the new enabled state
  10894. * @see isEnabled
  10895. */
  10896. Node.prototype.setEnabled = function (value) {
  10897. this._isEnabled = value;
  10898. };
  10899. /**
  10900. * Is this node a descendant of the given node.
  10901. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10902. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10903. * @see parent
  10904. */
  10905. Node.prototype.isDescendantOf = function (ancestor) {
  10906. if (this.parent) {
  10907. if (this.parent === ancestor) {
  10908. return true;
  10909. }
  10910. return this.parent.isDescendantOf(ancestor);
  10911. }
  10912. return false;
  10913. };
  10914. /**
  10915. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10916. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10917. * @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.
  10918. * @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.
  10919. */
  10920. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10921. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10922. if (!this._children) {
  10923. return;
  10924. }
  10925. for (var index = 0; index < this._children.length; index++) {
  10926. var item = this._children[index];
  10927. if (!predicate || predicate(item)) {
  10928. results.push(item);
  10929. }
  10930. if (!directDescendantsOnly) {
  10931. item._getDescendants(results, false, predicate);
  10932. }
  10933. }
  10934. };
  10935. /**
  10936. * Will return all nodes that have this node as ascendant.
  10937. * @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.
  10938. * @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.
  10939. * @return {BABYLON.Node[]} all children nodes of all types.
  10940. */
  10941. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10942. var results = [];
  10943. this._getDescendants(results, directDescendantsOnly, predicate);
  10944. return results;
  10945. };
  10946. /**
  10947. * Get all child-meshes of this node.
  10948. */
  10949. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10950. var results = [];
  10951. this._getDescendants(results, directDecendantsOnly, function (node) {
  10952. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10953. });
  10954. return results;
  10955. };
  10956. /**
  10957. * Get all direct children of this node.
  10958. */
  10959. Node.prototype.getChildren = function (predicate) {
  10960. return this.getDescendants(true, predicate);
  10961. };
  10962. Node.prototype._setReady = function (state) {
  10963. if (state === this._isReady) {
  10964. return;
  10965. }
  10966. if (!state) {
  10967. this._isReady = false;
  10968. return;
  10969. }
  10970. this._isReady = true;
  10971. if (this.onReady) {
  10972. this.onReady(this);
  10973. }
  10974. };
  10975. Node.prototype.getAnimationByName = function (name) {
  10976. for (var i = 0; i < this.animations.length; i++) {
  10977. var animation = this.animations[i];
  10978. if (animation.name === name) {
  10979. return animation;
  10980. }
  10981. }
  10982. return null;
  10983. };
  10984. Node.prototype.createAnimationRange = function (name, from, to) {
  10985. // check name not already in use
  10986. if (!this._ranges[name]) {
  10987. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10988. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10989. if (this.animations[i]) {
  10990. this.animations[i].createRange(name, from, to);
  10991. }
  10992. }
  10993. }
  10994. };
  10995. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10996. if (deleteFrames === void 0) { deleteFrames = true; }
  10997. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10998. if (this.animations[i]) {
  10999. this.animations[i].deleteRange(name, deleteFrames);
  11000. }
  11001. }
  11002. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11003. };
  11004. Node.prototype.getAnimationRange = function (name) {
  11005. return this._ranges[name];
  11006. };
  11007. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11008. var range = this.getAnimationRange(name);
  11009. if (!range) {
  11010. return null;
  11011. }
  11012. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11013. };
  11014. Node.prototype.serializeAnimationRanges = function () {
  11015. var serializationRanges = [];
  11016. for (var name in this._ranges) {
  11017. var range = {};
  11018. range.name = name;
  11019. range.from = this._ranges[name].from;
  11020. range.to = this._ranges[name].to;
  11021. serializationRanges.push(range);
  11022. }
  11023. return serializationRanges;
  11024. };
  11025. Node.prototype.dispose = function () {
  11026. this.parent = null;
  11027. // Callback
  11028. this.onDisposeObservable.notifyObservers(this);
  11029. this.onDisposeObservable.clear();
  11030. };
  11031. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11032. if (parsedNode.ranges) {
  11033. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11034. var data = parsedNode.ranges[index];
  11035. node.createAnimationRange(data.name, data.from, data.to);
  11036. }
  11037. }
  11038. };
  11039. return Node;
  11040. }());
  11041. __decorate([
  11042. BABYLON.serialize()
  11043. ], Node.prototype, "name", void 0);
  11044. __decorate([
  11045. BABYLON.serialize()
  11046. ], Node.prototype, "id", void 0);
  11047. __decorate([
  11048. BABYLON.serialize()
  11049. ], Node.prototype, "uniqueId", void 0);
  11050. __decorate([
  11051. BABYLON.serialize()
  11052. ], Node.prototype, "state", void 0);
  11053. __decorate([
  11054. BABYLON.serialize()
  11055. ], Node.prototype, "metadata", void 0);
  11056. BABYLON.Node = Node;
  11057. })(BABYLON || (BABYLON = {}));
  11058. //# sourceMappingURL=babylon.node.js.map
  11059. var BABYLON;
  11060. (function (BABYLON) {
  11061. var BoundingSphere = (function () {
  11062. function BoundingSphere(minimum, maximum) {
  11063. this.minimum = minimum;
  11064. this.maximum = maximum;
  11065. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11066. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11067. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11068. this.radius = distance * 0.5;
  11069. this.centerWorld = BABYLON.Vector3.Zero();
  11070. this._update(BABYLON.Matrix.Identity());
  11071. }
  11072. // Methods
  11073. BoundingSphere.prototype._update = function (world) {
  11074. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11075. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11076. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11077. };
  11078. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11079. for (var i = 0; i < 6; i++) {
  11080. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11081. return false;
  11082. }
  11083. return true;
  11084. };
  11085. BoundingSphere.prototype.intersectsPoint = function (point) {
  11086. var x = this.centerWorld.x - point.x;
  11087. var y = this.centerWorld.y - point.y;
  11088. var z = this.centerWorld.z - point.z;
  11089. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11090. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11091. return false;
  11092. return true;
  11093. };
  11094. // Statics
  11095. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11096. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11097. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11098. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11099. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11100. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11101. return false;
  11102. return true;
  11103. };
  11104. return BoundingSphere;
  11105. }());
  11106. BABYLON.BoundingSphere = BoundingSphere;
  11107. })(BABYLON || (BABYLON = {}));
  11108. //# sourceMappingURL=babylon.boundingSphere.js.map
  11109. var BABYLON;
  11110. (function (BABYLON) {
  11111. var BoundingBox = (function () {
  11112. function BoundingBox(minimum, maximum) {
  11113. this.minimum = minimum;
  11114. this.maximum = maximum;
  11115. this.vectors = new Array();
  11116. this.vectorsWorld = new Array();
  11117. // Bounding vectors
  11118. this.vectors.push(this.minimum.clone());
  11119. this.vectors.push(this.maximum.clone());
  11120. this.vectors.push(this.minimum.clone());
  11121. this.vectors[2].x = this.maximum.x;
  11122. this.vectors.push(this.minimum.clone());
  11123. this.vectors[3].y = this.maximum.y;
  11124. this.vectors.push(this.minimum.clone());
  11125. this.vectors[4].z = this.maximum.z;
  11126. this.vectors.push(this.maximum.clone());
  11127. this.vectors[5].z = this.minimum.z;
  11128. this.vectors.push(this.maximum.clone());
  11129. this.vectors[6].x = this.minimum.x;
  11130. this.vectors.push(this.maximum.clone());
  11131. this.vectors[7].y = this.minimum.y;
  11132. // OBB
  11133. this.center = this.maximum.add(this.minimum).scale(0.5);
  11134. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11135. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11136. // World
  11137. for (var index = 0; index < this.vectors.length; index++) {
  11138. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11139. }
  11140. this.minimumWorld = BABYLON.Vector3.Zero();
  11141. this.maximumWorld = BABYLON.Vector3.Zero();
  11142. this.centerWorld = BABYLON.Vector3.Zero();
  11143. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11144. this._update(BABYLON.Matrix.Identity());
  11145. }
  11146. // Methods
  11147. BoundingBox.prototype.getWorldMatrix = function () {
  11148. return this._worldMatrix;
  11149. };
  11150. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11151. this._worldMatrix.copyFrom(matrix);
  11152. return this;
  11153. };
  11154. BoundingBox.prototype._update = function (world) {
  11155. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11156. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11157. for (var index = 0; index < this.vectors.length; index++) {
  11158. var v = this.vectorsWorld[index];
  11159. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11160. if (v.x < this.minimumWorld.x)
  11161. this.minimumWorld.x = v.x;
  11162. if (v.y < this.minimumWorld.y)
  11163. this.minimumWorld.y = v.y;
  11164. if (v.z < this.minimumWorld.z)
  11165. this.minimumWorld.z = v.z;
  11166. if (v.x > this.maximumWorld.x)
  11167. this.maximumWorld.x = v.x;
  11168. if (v.y > this.maximumWorld.y)
  11169. this.maximumWorld.y = v.y;
  11170. if (v.z > this.maximumWorld.z)
  11171. this.maximumWorld.z = v.z;
  11172. }
  11173. // Extend
  11174. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11175. this.extendSizeWorld.scaleInPlace(0.5);
  11176. // OBB
  11177. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11178. this.centerWorld.scaleInPlace(0.5);
  11179. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11180. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11181. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11182. this._worldMatrix = world;
  11183. };
  11184. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11185. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11186. };
  11187. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11188. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11189. };
  11190. BoundingBox.prototype.intersectsPoint = function (point) {
  11191. var delta = -BABYLON.Epsilon;
  11192. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11193. return false;
  11194. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11195. return false;
  11196. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11197. return false;
  11198. return true;
  11199. };
  11200. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11201. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11202. };
  11203. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11204. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11205. return false;
  11206. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11207. return false;
  11208. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11209. return false;
  11210. return true;
  11211. };
  11212. // Statics
  11213. BoundingBox.Intersects = function (box0, box1) {
  11214. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11215. return false;
  11216. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11217. return false;
  11218. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11219. return false;
  11220. return true;
  11221. };
  11222. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11223. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11224. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11225. return (num <= (sphereRadius * sphereRadius));
  11226. };
  11227. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11228. for (var p = 0; p < 6; p++) {
  11229. for (var i = 0; i < 8; i++) {
  11230. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11231. return false;
  11232. }
  11233. }
  11234. }
  11235. return true;
  11236. };
  11237. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11238. for (var p = 0; p < 6; p++) {
  11239. var inCount = 8;
  11240. for (var i = 0; i < 8; i++) {
  11241. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11242. --inCount;
  11243. }
  11244. else {
  11245. break;
  11246. }
  11247. }
  11248. if (inCount === 0)
  11249. return false;
  11250. }
  11251. return true;
  11252. };
  11253. return BoundingBox;
  11254. }());
  11255. BABYLON.BoundingBox = BoundingBox;
  11256. })(BABYLON || (BABYLON = {}));
  11257. //# sourceMappingURL=babylon.boundingBox.js.map
  11258. var BABYLON;
  11259. (function (BABYLON) {
  11260. var computeBoxExtents = function (axis, box) {
  11261. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11262. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11263. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11264. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11265. var r = r0 + r1 + r2;
  11266. return {
  11267. min: p - r,
  11268. max: p + r
  11269. };
  11270. };
  11271. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11272. var axisOverlap = function (axis, box0, box1) {
  11273. var result0 = computeBoxExtents(axis, box0);
  11274. var result1 = computeBoxExtents(axis, box1);
  11275. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11276. };
  11277. var BoundingInfo = (function () {
  11278. function BoundingInfo(minimum, maximum) {
  11279. this.minimum = minimum;
  11280. this.maximum = maximum;
  11281. this._isLocked = false;
  11282. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11283. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11284. }
  11285. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11286. get: function () {
  11287. return this._isLocked;
  11288. },
  11289. set: function (value) {
  11290. this._isLocked = value;
  11291. },
  11292. enumerable: true,
  11293. configurable: true
  11294. });
  11295. // Methods
  11296. BoundingInfo.prototype.update = function (world) {
  11297. if (this._isLocked) {
  11298. return;
  11299. }
  11300. this.boundingBox._update(world);
  11301. this.boundingSphere._update(world);
  11302. };
  11303. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11304. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11305. return false;
  11306. return this.boundingBox.isInFrustum(frustumPlanes);
  11307. };
  11308. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11309. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11310. };
  11311. BoundingInfo.prototype._checkCollision = function (collider) {
  11312. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11313. };
  11314. BoundingInfo.prototype.intersectsPoint = function (point) {
  11315. if (!this.boundingSphere.centerWorld) {
  11316. return false;
  11317. }
  11318. if (!this.boundingSphere.intersectsPoint(point)) {
  11319. return false;
  11320. }
  11321. if (!this.boundingBox.intersectsPoint(point)) {
  11322. return false;
  11323. }
  11324. return true;
  11325. };
  11326. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11327. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11328. return false;
  11329. }
  11330. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11331. return false;
  11332. }
  11333. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11334. return false;
  11335. }
  11336. if (!precise) {
  11337. return true;
  11338. }
  11339. var box0 = this.boundingBox;
  11340. var box1 = boundingInfo.boundingBox;
  11341. if (!axisOverlap(box0.directions[0], box0, box1))
  11342. return false;
  11343. if (!axisOverlap(box0.directions[1], box0, box1))
  11344. return false;
  11345. if (!axisOverlap(box0.directions[2], box0, box1))
  11346. return false;
  11347. if (!axisOverlap(box1.directions[0], box0, box1))
  11348. return false;
  11349. if (!axisOverlap(box1.directions[1], box0, box1))
  11350. return false;
  11351. if (!axisOverlap(box1.directions[2], box0, box1))
  11352. return false;
  11353. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11354. return false;
  11355. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11356. return false;
  11357. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11358. return false;
  11359. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11360. return false;
  11361. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11362. return false;
  11363. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11364. return false;
  11365. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11366. return false;
  11367. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11368. return false;
  11369. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11370. return false;
  11371. return true;
  11372. };
  11373. return BoundingInfo;
  11374. }());
  11375. BABYLON.BoundingInfo = BoundingInfo;
  11376. })(BABYLON || (BABYLON = {}));
  11377. //# sourceMappingURL=babylon.boundingInfo.js.map
  11378. var BABYLON;
  11379. (function (BABYLON) {
  11380. var AbstractMesh = (function (_super) {
  11381. __extends(AbstractMesh, _super);
  11382. // Constructor
  11383. function AbstractMesh(name, scene) {
  11384. var _this = _super.call(this, name, scene) || this;
  11385. _this._facetNb = 0; // facet number
  11386. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11387. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11388. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11389. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11390. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11391. _this._subDiv = {
  11392. max: 1,
  11393. X: 1,
  11394. Y: 1,
  11395. Z: 1
  11396. };
  11397. // Events
  11398. /**
  11399. * An event triggered when this mesh collides with another one
  11400. * @type {BABYLON.Observable}
  11401. */
  11402. _this.onCollideObservable = new BABYLON.Observable();
  11403. /**
  11404. * An event triggered when the collision's position changes
  11405. * @type {BABYLON.Observable}
  11406. */
  11407. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11408. /**
  11409. * An event triggered after the world matrix is updated
  11410. * @type {BABYLON.Observable}
  11411. */
  11412. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11413. /**
  11414. * An event triggered when material is changed
  11415. * @type {BABYLON.Observable}
  11416. */
  11417. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11418. // Properties
  11419. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11420. _this.position = BABYLON.Vector3.Zero();
  11421. _this._rotation = BABYLON.Vector3.Zero();
  11422. _this._scaling = BABYLON.Vector3.One();
  11423. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11424. _this.visibility = 1.0;
  11425. _this.alphaIndex = Number.MAX_VALUE;
  11426. _this.infiniteDistance = false;
  11427. _this.isVisible = true;
  11428. _this.isPickable = true;
  11429. _this.showBoundingBox = false;
  11430. _this.showSubMeshesBoundingBox = false;
  11431. _this.isBlocker = false;
  11432. _this.enablePointerMoveEvents = false;
  11433. _this.renderingGroupId = 0;
  11434. _this._receiveShadows = false;
  11435. _this.renderOutline = false;
  11436. _this.outlineColor = BABYLON.Color3.Red();
  11437. _this.outlineWidth = 0.02;
  11438. _this.renderOverlay = false;
  11439. _this.overlayColor = BABYLON.Color3.Red();
  11440. _this.overlayAlpha = 0.5;
  11441. _this._hasVertexAlpha = false;
  11442. _this._useVertexColors = true;
  11443. _this._computeBonesUsingShaders = true;
  11444. _this._numBoneInfluencers = 4;
  11445. _this._applyFog = true;
  11446. _this.scalingDeterminant = 1;
  11447. _this.useOctreeForRenderingSelection = true;
  11448. _this.useOctreeForPicking = true;
  11449. _this.useOctreeForCollisions = true;
  11450. _this.layerMask = 0x0FFFFFFF;
  11451. /**
  11452. * True if the mesh must be rendered in any case.
  11453. */
  11454. _this.alwaysSelectAsActiveMesh = false;
  11455. // Collisions
  11456. _this._checkCollisions = false;
  11457. _this._collisionMask = -1;
  11458. _this._collisionGroup = -1;
  11459. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11460. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11461. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11462. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11463. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11464. // Edges
  11465. _this.edgesWidth = 1;
  11466. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11467. // Cache
  11468. _this._localWorld = BABYLON.Matrix.Zero();
  11469. _this._worldMatrix = BABYLON.Matrix.Zero();
  11470. _this._absolutePosition = BABYLON.Vector3.Zero();
  11471. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11472. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11473. _this._isDirty = false;
  11474. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11475. _this._isDisposed = false;
  11476. _this._renderId = 0;
  11477. _this._intersectionsInProgress = new Array();
  11478. _this._isWorldMatrixFrozen = false;
  11479. _this._unIndexed = false;
  11480. _this._lightSources = new Array();
  11481. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11482. if (collidedMesh === void 0) { collidedMesh = null; }
  11483. //TODO move this to the collision coordinator!
  11484. if (_this.getScene().workerCollisions)
  11485. newPosition.multiplyInPlace(_this._collider.radius);
  11486. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11487. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11488. _this.position.addInPlace(_this._diffPositionForCollisions);
  11489. }
  11490. if (collidedMesh) {
  11491. _this.onCollideObservable.notifyObservers(collidedMesh);
  11492. }
  11493. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11494. };
  11495. _this.getScene().addMesh(_this);
  11496. _this._resyncLightSources();
  11497. return _this;
  11498. }
  11499. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11500. get: function () {
  11501. return AbstractMesh._BILLBOARDMODE_NONE;
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11507. get: function () {
  11508. return AbstractMesh._BILLBOARDMODE_X;
  11509. },
  11510. enumerable: true,
  11511. configurable: true
  11512. });
  11513. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11514. get: function () {
  11515. return AbstractMesh._BILLBOARDMODE_Y;
  11516. },
  11517. enumerable: true,
  11518. configurable: true
  11519. });
  11520. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11521. get: function () {
  11522. return AbstractMesh._BILLBOARDMODE_Z;
  11523. },
  11524. enumerable: true,
  11525. configurable: true
  11526. });
  11527. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11528. get: function () {
  11529. return AbstractMesh._BILLBOARDMODE_ALL;
  11530. },
  11531. enumerable: true,
  11532. configurable: true
  11533. });
  11534. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11535. /**
  11536. * Read-only : the number of facets in the mesh
  11537. */
  11538. get: function () {
  11539. return this._facetNb;
  11540. },
  11541. enumerable: true,
  11542. configurable: true
  11543. });
  11544. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11545. /**
  11546. * The number (integer) of subdivisions per axis in the partioning space
  11547. */
  11548. get: function () {
  11549. return this._partitioningSubdivisions;
  11550. },
  11551. set: function (nb) {
  11552. this._partitioningSubdivisions = nb;
  11553. },
  11554. enumerable: true,
  11555. configurable: true
  11556. });
  11557. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11558. /**
  11559. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11560. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11561. */
  11562. get: function () {
  11563. return this._partitioningBBoxRatio;
  11564. },
  11565. set: function (ratio) {
  11566. this._partitioningBBoxRatio = ratio;
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11572. /**
  11573. * Read-only boolean : is the feature facetData enabled ?
  11574. */
  11575. get: function () {
  11576. return this._facetDataEnabled;
  11577. },
  11578. enumerable: true,
  11579. configurable: true
  11580. });
  11581. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11582. set: function (callback) {
  11583. if (this._onCollideObserver) {
  11584. this.onCollideObservable.remove(this._onCollideObserver);
  11585. }
  11586. this._onCollideObserver = this.onCollideObservable.add(callback);
  11587. },
  11588. enumerable: true,
  11589. configurable: true
  11590. });
  11591. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11592. set: function (callback) {
  11593. if (this._onCollisionPositionChangeObserver) {
  11594. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11595. }
  11596. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11597. },
  11598. enumerable: true,
  11599. configurable: true
  11600. });
  11601. Object.defineProperty(AbstractMesh.prototype, "material", {
  11602. get: function () {
  11603. return this._material;
  11604. },
  11605. set: function (value) {
  11606. if (this._material === value) {
  11607. return;
  11608. }
  11609. this._material = value;
  11610. if (this.onMaterialChangedObservable.hasObservers) {
  11611. this.onMaterialChangedObservable.notifyObservers(this);
  11612. }
  11613. if (!this.subMeshes) {
  11614. return;
  11615. }
  11616. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11617. var subMesh = _a[_i];
  11618. subMesh.setEffect(null);
  11619. }
  11620. },
  11621. enumerable: true,
  11622. configurable: true
  11623. });
  11624. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11625. get: function () {
  11626. return this._receiveShadows;
  11627. },
  11628. set: function (value) {
  11629. if (this._receiveShadows === value) {
  11630. return;
  11631. }
  11632. this._receiveShadows = value;
  11633. this._markSubMeshesAsLightDirty();
  11634. },
  11635. enumerable: true,
  11636. configurable: true
  11637. });
  11638. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11639. get: function () {
  11640. return this._hasVertexAlpha;
  11641. },
  11642. set: function (value) {
  11643. if (this._hasVertexAlpha === value) {
  11644. return;
  11645. }
  11646. this._hasVertexAlpha = value;
  11647. this._markSubMeshesAsAttributesDirty();
  11648. },
  11649. enumerable: true,
  11650. configurable: true
  11651. });
  11652. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11653. get: function () {
  11654. return this._useVertexColors;
  11655. },
  11656. set: function (value) {
  11657. if (this._useVertexColors === value) {
  11658. return;
  11659. }
  11660. this._useVertexColors = value;
  11661. this._markSubMeshesAsAttributesDirty();
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11667. get: function () {
  11668. return this._computeBonesUsingShaders;
  11669. },
  11670. set: function (value) {
  11671. if (this._computeBonesUsingShaders === value) {
  11672. return;
  11673. }
  11674. this._computeBonesUsingShaders = value;
  11675. this._markSubMeshesAsAttributesDirty();
  11676. },
  11677. enumerable: true,
  11678. configurable: true
  11679. });
  11680. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11681. get: function () {
  11682. return this._numBoneInfluencers;
  11683. },
  11684. set: function (value) {
  11685. if (this._numBoneInfluencers === value) {
  11686. return;
  11687. }
  11688. this._numBoneInfluencers = value;
  11689. this._markSubMeshesAsAttributesDirty();
  11690. },
  11691. enumerable: true,
  11692. configurable: true
  11693. });
  11694. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11695. get: function () {
  11696. return this._applyFog;
  11697. },
  11698. set: function (value) {
  11699. if (this._applyFog === value) {
  11700. return;
  11701. }
  11702. this._applyFog = value;
  11703. this._markSubMeshesAsMiscDirty();
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11709. get: function () {
  11710. return this._collisionMask;
  11711. },
  11712. set: function (mask) {
  11713. this._collisionMask = !isNaN(mask) ? mask : -1;
  11714. },
  11715. enumerable: true,
  11716. configurable: true
  11717. });
  11718. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11719. get: function () {
  11720. return this._collisionGroup;
  11721. },
  11722. set: function (mask) {
  11723. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11729. get: function () {
  11730. return null;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11736. get: function () {
  11737. return this._skeleton;
  11738. },
  11739. set: function (value) {
  11740. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11741. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11742. }
  11743. if (value && value.needInitialSkinMatrix) {
  11744. value._registerMeshWithPoseMatrix(this);
  11745. }
  11746. this._skeleton = value;
  11747. if (!this._skeleton) {
  11748. this._bonesTransformMatrices = null;
  11749. }
  11750. this._markSubMeshesAsAttributesDirty();
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. /**
  11756. * Boolean : true if the mesh has been disposed.
  11757. */
  11758. AbstractMesh.prototype.isDisposed = function () {
  11759. return this._isDisposed;
  11760. };
  11761. /**
  11762. * Returns the string "AbstractMesh"
  11763. */
  11764. AbstractMesh.prototype.getClassName = function () {
  11765. return "AbstractMesh";
  11766. };
  11767. /**
  11768. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11769. */
  11770. AbstractMesh.prototype.toString = function (fullDetails) {
  11771. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11772. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11773. if (this._skeleton) {
  11774. ret += ", skeleton: " + this._skeleton.name;
  11775. }
  11776. if (fullDetails) {
  11777. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11778. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11779. }
  11780. return ret;
  11781. };
  11782. AbstractMesh.prototype._resyncLightSources = function () {
  11783. this._lightSources.length = 0;
  11784. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11785. var light = _a[_i];
  11786. if (!light.isEnabled()) {
  11787. continue;
  11788. }
  11789. if (light.canAffectMesh(this)) {
  11790. this._lightSources.push(light);
  11791. }
  11792. }
  11793. this._markSubMeshesAsLightDirty();
  11794. };
  11795. AbstractMesh.prototype._resyncLighSource = function (light) {
  11796. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11797. var index = this._lightSources.indexOf(light);
  11798. if (index === -1) {
  11799. if (!isIn) {
  11800. return;
  11801. }
  11802. this._lightSources.push(light);
  11803. }
  11804. else {
  11805. if (isIn) {
  11806. return;
  11807. }
  11808. this._lightSources.splice(index, 1);
  11809. }
  11810. this._markSubMeshesAsLightDirty();
  11811. };
  11812. AbstractMesh.prototype._removeLightSource = function (light) {
  11813. var index = this._lightSources.indexOf(light);
  11814. if (index === -1) {
  11815. return;
  11816. }
  11817. this._lightSources.splice(index, 1);
  11818. };
  11819. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11820. if (!this.subMeshes) {
  11821. return;
  11822. }
  11823. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11824. var subMesh = _a[_i];
  11825. if (subMesh._materialDefines) {
  11826. func(subMesh._materialDefines);
  11827. }
  11828. }
  11829. };
  11830. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11831. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11832. };
  11833. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11834. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11835. };
  11836. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11837. if (!this.subMeshes) {
  11838. return;
  11839. }
  11840. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11841. var subMesh = _a[_i];
  11842. var material = subMesh.getMaterial();
  11843. if (material) {
  11844. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11845. }
  11846. }
  11847. };
  11848. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11849. /**
  11850. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11851. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11852. * Default : (0.0, 0.0, 0.0)
  11853. */
  11854. get: function () {
  11855. return this._rotation;
  11856. },
  11857. set: function (newRotation) {
  11858. this._rotation = newRotation;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11864. /**
  11865. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11866. * Default : (1.0, 1.0, 1.0)
  11867. */
  11868. get: function () {
  11869. return this._scaling;
  11870. },
  11871. set: function (newScaling) {
  11872. this._scaling = newScaling;
  11873. if (this.physicsImpostor) {
  11874. this.physicsImpostor.forceUpdate();
  11875. }
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11881. /**
  11882. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11883. * It's null by default.
  11884. * 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)
  11885. */
  11886. get: function () {
  11887. return this._rotationQuaternion;
  11888. },
  11889. set: function (quaternion) {
  11890. this._rotationQuaternion = quaternion;
  11891. //reset the rotation vector.
  11892. if (quaternion && this.rotation.length()) {
  11893. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11894. }
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. // Methods
  11900. /**
  11901. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11902. * Returns the AbstractMesh.
  11903. */
  11904. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11905. this._poseMatrix.copyFrom(matrix);
  11906. return this;
  11907. };
  11908. /**
  11909. * Returns the mesh Pose matrix.
  11910. * Returned object : Matrix
  11911. */
  11912. AbstractMesh.prototype.getPoseMatrix = function () {
  11913. return this._poseMatrix;
  11914. };
  11915. /**
  11916. * Disables the mesh edger rendering mode.
  11917. * Returns the AbstractMesh.
  11918. */
  11919. AbstractMesh.prototype.disableEdgesRendering = function () {
  11920. if (this._edgesRenderer !== undefined) {
  11921. this._edgesRenderer.dispose();
  11922. this._edgesRenderer = undefined;
  11923. }
  11924. return this;
  11925. };
  11926. /**
  11927. * Enables the edge rendering mode on the mesh.
  11928. * This mode makes the mesh edges visible.
  11929. * Returns the AbstractMesh.
  11930. */
  11931. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11932. if (epsilon === void 0) { epsilon = 0.95; }
  11933. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11934. this.disableEdgesRendering();
  11935. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11936. return this;
  11937. };
  11938. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11939. /**
  11940. * Returns true if the mesh is blocked. Used by the class Mesh.
  11941. * Returns the boolean `false` by default.
  11942. */
  11943. get: function () {
  11944. return false;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. /**
  11950. * Returns the mesh itself by default, used by the class Mesh.
  11951. * Returned type : AbstractMesh
  11952. */
  11953. AbstractMesh.prototype.getLOD = function (camera) {
  11954. return this;
  11955. };
  11956. /**
  11957. * Returns 0 by default, used by the class Mesh.
  11958. * Returns an integer.
  11959. */
  11960. AbstractMesh.prototype.getTotalVertices = function () {
  11961. return 0;
  11962. };
  11963. /**
  11964. * Returns null by default, used by the class Mesh.
  11965. * Returned type : integer array
  11966. */
  11967. AbstractMesh.prototype.getIndices = function () {
  11968. return null;
  11969. };
  11970. /**
  11971. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11972. * Returned type : float array or Float32Array
  11973. */
  11974. AbstractMesh.prototype.getVerticesData = function (kind) {
  11975. return null;
  11976. };
  11977. /**
  11978. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11979. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11980. * The `data` are either a numeric array either a Float32Array.
  11981. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11982. * 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).
  11983. * Note that a new underlying VertexBuffer object is created each call.
  11984. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11985. *
  11986. * Possible `kind` values :
  11987. * - BABYLON.VertexBuffer.PositionKind
  11988. * - BABYLON.VertexBuffer.UVKind
  11989. * - BABYLON.VertexBuffer.UV2Kind
  11990. * - BABYLON.VertexBuffer.UV3Kind
  11991. * - BABYLON.VertexBuffer.UV4Kind
  11992. * - BABYLON.VertexBuffer.UV5Kind
  11993. * - BABYLON.VertexBuffer.UV6Kind
  11994. * - BABYLON.VertexBuffer.ColorKind
  11995. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11996. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11997. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11998. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11999. *
  12000. * Returns the Mesh.
  12001. */
  12002. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12003. return null;
  12004. };
  12005. /**
  12006. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12007. * If the mesh has no geometry, it is simply returned as it is.
  12008. * The `data` are either a numeric array either a Float32Array.
  12009. * No new underlying VertexBuffer object is created.
  12010. * 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.
  12011. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12012. *
  12013. * Possible `kind` values :
  12014. * - BABYLON.VertexBuffer.PositionKind
  12015. * - BABYLON.VertexBuffer.UVKind
  12016. * - BABYLON.VertexBuffer.UV2Kind
  12017. * - BABYLON.VertexBuffer.UV3Kind
  12018. * - BABYLON.VertexBuffer.UV4Kind
  12019. * - BABYLON.VertexBuffer.UV5Kind
  12020. * - BABYLON.VertexBuffer.UV6Kind
  12021. * - BABYLON.VertexBuffer.ColorKind
  12022. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12023. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12024. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12025. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12026. *
  12027. * Returns the Mesh.
  12028. */
  12029. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12030. return null;
  12031. };
  12032. /**
  12033. * Sets the mesh indices.
  12034. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12035. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12036. * This method creates a new index buffer each call.
  12037. * Returns the Mesh.
  12038. */
  12039. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12040. return null;
  12041. };
  12042. /** Returns false by default, used by the class Mesh.
  12043. * Returns a boolean
  12044. */
  12045. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12046. return false;
  12047. };
  12048. /**
  12049. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12050. * Returns a BoundingInfo
  12051. */
  12052. AbstractMesh.prototype.getBoundingInfo = function () {
  12053. if (this._masterMesh) {
  12054. return this._masterMesh.getBoundingInfo();
  12055. }
  12056. if (!this._boundingInfo) {
  12057. this._updateBoundingInfo();
  12058. }
  12059. return this._boundingInfo;
  12060. };
  12061. /**
  12062. * Sets a mesh new object BoundingInfo.
  12063. * Returns the AbstractMesh.
  12064. */
  12065. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12066. this._boundingInfo = boundingInfo;
  12067. return this;
  12068. };
  12069. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12070. get: function () {
  12071. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. AbstractMesh.prototype._preActivate = function () {
  12077. };
  12078. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12079. };
  12080. AbstractMesh.prototype._activate = function (renderId) {
  12081. this._renderId = renderId;
  12082. };
  12083. /**
  12084. * Returns the last update of the World matrix
  12085. * Returns a Matrix.
  12086. */
  12087. AbstractMesh.prototype.getWorldMatrix = function () {
  12088. if (this._masterMesh) {
  12089. return this._masterMesh.getWorldMatrix();
  12090. }
  12091. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12092. this.computeWorldMatrix();
  12093. }
  12094. return this._worldMatrix;
  12095. };
  12096. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12097. /**
  12098. * Returns directly the last state of the mesh World matrix.
  12099. * A Matrix is returned.
  12100. */
  12101. get: function () {
  12102. return this._worldMatrix;
  12103. },
  12104. enumerable: true,
  12105. configurable: true
  12106. });
  12107. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12108. /**
  12109. * Returns the current mesh absolute position.
  12110. * Retuns a Vector3.
  12111. */
  12112. get: function () {
  12113. return this._absolutePosition;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. /**
  12119. * Prevents the World matrix to be computed any longer.
  12120. * Returns the AbstractMesh.
  12121. */
  12122. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12123. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12124. this.computeWorldMatrix(true);
  12125. this._isWorldMatrixFrozen = true;
  12126. return this;
  12127. };
  12128. /**
  12129. * Allows back the World matrix computation.
  12130. * Returns the AbstractMesh.
  12131. */
  12132. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12133. this._isWorldMatrixFrozen = false;
  12134. this.computeWorldMatrix(true);
  12135. return this;
  12136. };
  12137. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12138. /**
  12139. * True if the World matrix has been frozen.
  12140. * Returns a boolean.
  12141. */
  12142. get: function () {
  12143. return this._isWorldMatrixFrozen;
  12144. },
  12145. enumerable: true,
  12146. configurable: true
  12147. });
  12148. /**
  12149. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12150. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12151. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12152. * The passed axis is also normalized.
  12153. * Returns the AbstractMesh.
  12154. */
  12155. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12156. axis.normalize();
  12157. if (!this.rotationQuaternion) {
  12158. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12159. this.rotation = BABYLON.Vector3.Zero();
  12160. }
  12161. var rotationQuaternion;
  12162. if (!space || space === BABYLON.Space.LOCAL) {
  12163. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12164. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12165. }
  12166. else {
  12167. if (this.parent) {
  12168. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12169. invertParentWorldMatrix.invert();
  12170. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12171. }
  12172. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12173. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12174. }
  12175. return this;
  12176. };
  12177. /**
  12178. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12179. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12180. * The passed axis is also normalized.
  12181. * Returns the AbstractMesh.
  12182. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12183. */
  12184. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12185. axis.normalize();
  12186. if (!this.rotationQuaternion) {
  12187. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12188. this.rotation.copyFromFloats(0, 0, 0);
  12189. }
  12190. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12191. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12192. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12193. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12194. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12195. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12196. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12197. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12198. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  12199. return this;
  12200. };
  12201. /**
  12202. * Translates the mesh along the axis vector for the passed distance in the given space.
  12203. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12204. * Returns the AbstractMesh.
  12205. */
  12206. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12207. var displacementVector = axis.scale(distance);
  12208. if (!space || space === BABYLON.Space.LOCAL) {
  12209. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12210. this.setPositionWithLocalVector(tempV3);
  12211. }
  12212. else {
  12213. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12214. }
  12215. return this;
  12216. };
  12217. /**
  12218. * Adds a rotation step to the mesh current rotation.
  12219. * x, y, z are Euler angles expressed in radians.
  12220. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12221. * This means this rotation is made in the mesh local space only.
  12222. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12223. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12224. * ```javascript
  12225. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12226. * ```
  12227. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12228. * 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.
  12229. * Returns the AbstractMesh.
  12230. */
  12231. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12232. var rotationQuaternion;
  12233. if (this.rotationQuaternion) {
  12234. rotationQuaternion = this.rotationQuaternion;
  12235. }
  12236. else {
  12237. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12238. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12239. }
  12240. var accumulation = BABYLON.Tmp.Quaternion[0];
  12241. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12242. rotationQuaternion.multiplyInPlace(accumulation);
  12243. if (!this.rotationQuaternion) {
  12244. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12245. }
  12246. return this;
  12247. };
  12248. /**
  12249. * Retuns the mesh absolute position in the World.
  12250. * Returns a Vector3.
  12251. */
  12252. AbstractMesh.prototype.getAbsolutePosition = function () {
  12253. this.computeWorldMatrix();
  12254. return this._absolutePosition;
  12255. };
  12256. /**
  12257. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12258. * Returns the AbstractMesh.
  12259. */
  12260. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12261. if (!absolutePosition) {
  12262. return;
  12263. }
  12264. var absolutePositionX;
  12265. var absolutePositionY;
  12266. var absolutePositionZ;
  12267. if (absolutePosition.x === undefined) {
  12268. if (arguments.length < 3) {
  12269. return;
  12270. }
  12271. absolutePositionX = arguments[0];
  12272. absolutePositionY = arguments[1];
  12273. absolutePositionZ = arguments[2];
  12274. }
  12275. else {
  12276. absolutePositionX = absolutePosition.x;
  12277. absolutePositionY = absolutePosition.y;
  12278. absolutePositionZ = absolutePosition.z;
  12279. }
  12280. if (this.parent) {
  12281. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12282. invertParentWorldMatrix.invert();
  12283. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12284. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12285. }
  12286. else {
  12287. this.position.x = absolutePositionX;
  12288. this.position.y = absolutePositionY;
  12289. this.position.z = absolutePositionZ;
  12290. }
  12291. return this;
  12292. };
  12293. // ================================== Point of View Movement =================================
  12294. /**
  12295. * Perform relative position change from the point of view of behind the front of the mesh.
  12296. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12297. * Supports definition of mesh facing forward or backward.
  12298. * @param {number} amountRight
  12299. * @param {number} amountUp
  12300. * @param {number} amountForward
  12301. *
  12302. * Returns the AbstractMesh.
  12303. */
  12304. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12305. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12306. return this;
  12307. };
  12308. /**
  12309. * Calculate relative position change from the point of view of behind the front of the mesh.
  12310. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12311. * Supports definition of mesh facing forward or backward.
  12312. * @param {number} amountRight
  12313. * @param {number} amountUp
  12314. * @param {number} amountForward
  12315. *
  12316. * Returns a new Vector3.
  12317. */
  12318. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12319. var rotMatrix = new BABYLON.Matrix();
  12320. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12321. rotQuaternion.toRotationMatrix(rotMatrix);
  12322. var translationDelta = BABYLON.Vector3.Zero();
  12323. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12324. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12325. return translationDelta;
  12326. };
  12327. // ================================== Point of View Rotation =================================
  12328. /**
  12329. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12330. * Supports definition of mesh facing forward or backward.
  12331. * @param {number} flipBack
  12332. * @param {number} twirlClockwise
  12333. * @param {number} tiltRight
  12334. *
  12335. * Returns the AbstractMesh.
  12336. */
  12337. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12338. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12339. return this;
  12340. };
  12341. /**
  12342. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12343. * Supports definition of mesh facing forward or backward.
  12344. * @param {number} flipBack
  12345. * @param {number} twirlClockwise
  12346. * @param {number} tiltRight
  12347. *
  12348. * Returns a new Vector3.
  12349. */
  12350. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12351. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12352. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12353. };
  12354. /**
  12355. * Sets a new pivot matrix to the mesh.
  12356. * Returns the AbstractMesh.
  12357. */
  12358. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12359. this._pivotMatrix = matrix;
  12360. this._cache.pivotMatrixUpdated = true;
  12361. return this;
  12362. };
  12363. /**
  12364. * Returns the mesh pivot matrix.
  12365. * Default : Identity.
  12366. * A Matrix is returned.
  12367. */
  12368. AbstractMesh.prototype.getPivotMatrix = function () {
  12369. return this._pivotMatrix;
  12370. };
  12371. AbstractMesh.prototype._isSynchronized = function () {
  12372. if (this._isDirty) {
  12373. return false;
  12374. }
  12375. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12376. return false;
  12377. if (this._cache.pivotMatrixUpdated) {
  12378. return false;
  12379. }
  12380. if (this.infiniteDistance) {
  12381. return false;
  12382. }
  12383. if (!this._cache.position.equals(this.position))
  12384. return false;
  12385. if (this.rotationQuaternion) {
  12386. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12387. return false;
  12388. }
  12389. if (!this._cache.rotation.equals(this.rotation))
  12390. return false;
  12391. if (!this._cache.scaling.equals(this.scaling))
  12392. return false;
  12393. return true;
  12394. };
  12395. AbstractMesh.prototype._initCache = function () {
  12396. _super.prototype._initCache.call(this);
  12397. this._cache.localMatrixUpdated = false;
  12398. this._cache.position = BABYLON.Vector3.Zero();
  12399. this._cache.scaling = BABYLON.Vector3.Zero();
  12400. this._cache.rotation = BABYLON.Vector3.Zero();
  12401. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12402. this._cache.billboardMode = -1;
  12403. };
  12404. AbstractMesh.prototype.markAsDirty = function (property) {
  12405. if (property === "rotation") {
  12406. this.rotationQuaternion = null;
  12407. }
  12408. this._currentRenderId = Number.MAX_VALUE;
  12409. this._isDirty = true;
  12410. return this;
  12411. };
  12412. /**
  12413. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12414. * Returns the AbstractMesh.
  12415. */
  12416. AbstractMesh.prototype._updateBoundingInfo = function () {
  12417. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12418. this._boundingInfo.update(this.worldMatrixFromCache);
  12419. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12420. return this;
  12421. };
  12422. /**
  12423. * Update a mesh's children BoundingInfo objects only.
  12424. * Returns the AbstractMesh.
  12425. */
  12426. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12427. if (!this.subMeshes) {
  12428. return;
  12429. }
  12430. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12431. var subMesh = this.subMeshes[subIndex];
  12432. if (!subMesh.IsGlobal) {
  12433. subMesh.updateBoundingInfo(matrix);
  12434. }
  12435. }
  12436. return this;
  12437. };
  12438. /**
  12439. * Computes the mesh World matrix and returns it.
  12440. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12441. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12442. * If the parameter `force`is set to `true`, the actual computation is done.
  12443. * Returns the mesh World Matrix.
  12444. */
  12445. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12446. if (this._isWorldMatrixFrozen) {
  12447. return this._worldMatrix;
  12448. }
  12449. if (!force && this.isSynchronized(true)) {
  12450. this._currentRenderId = this.getScene().getRenderId();
  12451. return this._worldMatrix;
  12452. }
  12453. this._cache.position.copyFrom(this.position);
  12454. this._cache.scaling.copyFrom(this.scaling);
  12455. this._cache.pivotMatrixUpdated = false;
  12456. this._cache.billboardMode = this.billboardMode;
  12457. this._currentRenderId = this.getScene().getRenderId();
  12458. this._isDirty = false;
  12459. // Scaling
  12460. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12461. // Rotation
  12462. //rotate, if quaternion is set and rotation was used
  12463. if (this.rotationQuaternion) {
  12464. var len = this.rotation.length();
  12465. if (len) {
  12466. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12467. this.rotation.copyFromFloats(0, 0, 0);
  12468. }
  12469. }
  12470. if (this.rotationQuaternion) {
  12471. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12472. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12473. }
  12474. else {
  12475. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12476. this._cache.rotation.copyFrom(this.rotation);
  12477. }
  12478. // Translation
  12479. if (this.infiniteDistance && !this.parent) {
  12480. var camera = this.getScene().activeCamera;
  12481. if (camera) {
  12482. var cameraWorldMatrix = camera.getWorldMatrix();
  12483. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12484. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12485. }
  12486. }
  12487. else {
  12488. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12489. }
  12490. // Composing transformations
  12491. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12492. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12493. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12494. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12495. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12496. // Need to decompose each rotation here
  12497. var currentPosition = BABYLON.Tmp.Vector3[3];
  12498. if (this.parent && this.parent.getWorldMatrix) {
  12499. if (this._meshToBoneReferal) {
  12500. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12501. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12502. }
  12503. else {
  12504. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12505. }
  12506. }
  12507. else {
  12508. currentPosition.copyFrom(this.position);
  12509. }
  12510. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12511. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12512. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12513. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12514. }
  12515. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12516. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12517. }
  12518. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12519. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12520. }
  12521. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12522. }
  12523. else {
  12524. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12525. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12526. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12527. }
  12528. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12529. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12530. }
  12531. // Local world
  12532. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12533. // Parent
  12534. if (this.parent && this.parent.getWorldMatrix) {
  12535. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12536. if (this._meshToBoneReferal) {
  12537. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12538. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12539. }
  12540. else {
  12541. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12542. }
  12543. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12544. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12545. this._worldMatrix.copyFrom(this._localWorld);
  12546. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12547. }
  12548. else {
  12549. if (this._meshToBoneReferal) {
  12550. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12551. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12552. }
  12553. else {
  12554. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12555. }
  12556. }
  12557. this._markSyncedWithParent();
  12558. }
  12559. else {
  12560. this._worldMatrix.copyFrom(this._localWorld);
  12561. }
  12562. // Bounding info
  12563. this._updateBoundingInfo();
  12564. // Absolute position
  12565. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12566. // Callbacks
  12567. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12568. if (!this._poseMatrix) {
  12569. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12570. }
  12571. return this._worldMatrix;
  12572. };
  12573. /**
  12574. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12575. * @param func: callback function to add
  12576. *
  12577. * Returns the AbstractMesh.
  12578. */
  12579. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12580. this.onAfterWorldMatrixUpdateObservable.add(func);
  12581. return this;
  12582. };
  12583. /**
  12584. * Removes a registered callback function.
  12585. * Returns the AbstractMesh.
  12586. */
  12587. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12588. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12589. return this;
  12590. };
  12591. /**
  12592. * Sets the mesh position in its local space.
  12593. * Returns the AbstractMesh.
  12594. */
  12595. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12596. this.computeWorldMatrix();
  12597. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12598. return this;
  12599. };
  12600. /**
  12601. * Returns the mesh position in the local space from the current World matrix values.
  12602. * Returns a new Vector3.
  12603. */
  12604. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12605. this.computeWorldMatrix();
  12606. var invLocalWorldMatrix = this._localWorld.clone();
  12607. invLocalWorldMatrix.invert();
  12608. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12609. };
  12610. /**
  12611. * Translates the mesh along the passed Vector3 in its local space.
  12612. * Returns the AbstractMesh.
  12613. */
  12614. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12615. this.computeWorldMatrix(true);
  12616. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12617. return this;
  12618. };
  12619. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12620. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12621. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12622. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12623. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12624. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12625. /// <returns>Mesh oriented towards targetMesh</returns>
  12626. if (yawCor === void 0) { yawCor = 0; }
  12627. if (pitchCor === void 0) { pitchCor = 0; }
  12628. if (rollCor === void 0) { rollCor = 0; }
  12629. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12630. var dv = AbstractMesh._lookAtVectorCache;
  12631. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12632. targetPoint.subtractToRef(pos, dv);
  12633. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12634. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12635. var pitch = Math.atan2(dv.y, len);
  12636. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12637. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12638. return this;
  12639. };
  12640. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12641. this._meshToBoneReferal = affectedMesh;
  12642. this.parent = bone;
  12643. if (bone.getWorldMatrix().determinant() < 0) {
  12644. this.scalingDeterminant *= -1;
  12645. }
  12646. return this;
  12647. };
  12648. AbstractMesh.prototype.detachFromBone = function () {
  12649. if (this.parent.getWorldMatrix().determinant() < 0) {
  12650. this.scalingDeterminant *= -1;
  12651. }
  12652. this._meshToBoneReferal = null;
  12653. this.parent = null;
  12654. return this;
  12655. };
  12656. /**
  12657. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12658. * A mesh is in the frustum if its bounding box intersects the frustum.
  12659. * Boolean returned.
  12660. */
  12661. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12662. return this._boundingInfo.isInFrustum(frustumPlanes);
  12663. };
  12664. /**
  12665. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12666. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12667. * Boolean returned.
  12668. */
  12669. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12670. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12671. ;
  12672. };
  12673. /**
  12674. * True if the mesh intersects another mesh or a SolidParticle object.
  12675. * 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)
  12676. * Returns a boolean.
  12677. */
  12678. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12679. if (!this._boundingInfo || !mesh._boundingInfo) {
  12680. return false;
  12681. }
  12682. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12683. };
  12684. /**
  12685. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12686. * Returns a boolean.
  12687. */
  12688. AbstractMesh.prototype.intersectsPoint = function (point) {
  12689. if (!this._boundingInfo) {
  12690. return false;
  12691. }
  12692. return this._boundingInfo.intersectsPoint(point);
  12693. };
  12694. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12695. return this.physicsImpostor;
  12696. };
  12697. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12698. if (!camera) {
  12699. camera = this.getScene().activeCamera;
  12700. }
  12701. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12702. };
  12703. /**
  12704. * Returns the distance from the mesh to the active camera.
  12705. * Returns a float.
  12706. */
  12707. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12708. if (!camera) {
  12709. camera = this.getScene().activeCamera;
  12710. }
  12711. return this.absolutePosition.subtract(camera.position).length();
  12712. };
  12713. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12714. if (!this.physicsImpostor) {
  12715. return;
  12716. }
  12717. this.physicsImpostor.applyImpulse(force, contactPoint);
  12718. return this;
  12719. };
  12720. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12721. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12722. return;
  12723. }
  12724. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12725. mainPivot: pivot1,
  12726. connectedPivot: pivot2,
  12727. nativeParams: options
  12728. });
  12729. return this;
  12730. };
  12731. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12732. // Collisions
  12733. /**
  12734. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12735. * Default `false`.
  12736. */
  12737. get: function () {
  12738. return this._checkCollisions;
  12739. },
  12740. set: function (collisionEnabled) {
  12741. this._checkCollisions = collisionEnabled;
  12742. if (this.getScene().workerCollisions) {
  12743. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12744. }
  12745. },
  12746. enumerable: true,
  12747. configurable: true
  12748. });
  12749. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12750. var globalPosition = this.getAbsolutePosition();
  12751. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12752. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12753. if (!this._collider) {
  12754. this._collider = new BABYLON.Collider();
  12755. }
  12756. this._collider.radius = this.ellipsoid;
  12757. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12758. return this;
  12759. };
  12760. // Submeshes octree
  12761. /**
  12762. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12763. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12764. * Returns an Octree of submeshes.
  12765. */
  12766. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12767. if (maxCapacity === void 0) { maxCapacity = 64; }
  12768. if (maxDepth === void 0) { maxDepth = 2; }
  12769. if (!this._submeshesOctree) {
  12770. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12771. }
  12772. this.computeWorldMatrix(true);
  12773. // Update octree
  12774. var bbox = this.getBoundingInfo().boundingBox;
  12775. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12776. return this._submeshesOctree;
  12777. };
  12778. // Collisions
  12779. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12780. this._generatePointsArray();
  12781. // Transformation
  12782. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12783. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12784. subMesh._lastColliderWorldVertices = [];
  12785. subMesh._trianglePlanes = [];
  12786. var start = subMesh.verticesStart;
  12787. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12788. for (var i = start; i < end; i++) {
  12789. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12790. }
  12791. }
  12792. // Collide
  12793. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12794. if (collider.collisionFound) {
  12795. collider.collidedMesh = this;
  12796. }
  12797. return this;
  12798. };
  12799. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12800. var subMeshes;
  12801. var len;
  12802. // Octrees
  12803. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12804. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12805. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12806. len = intersections.length;
  12807. subMeshes = intersections.data;
  12808. }
  12809. else {
  12810. subMeshes = this.subMeshes;
  12811. len = subMeshes.length;
  12812. }
  12813. for (var index = 0; index < len; index++) {
  12814. var subMesh = subMeshes[index];
  12815. // Bounding test
  12816. if (len > 1 && !subMesh._checkCollision(collider))
  12817. continue;
  12818. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12819. }
  12820. return this;
  12821. };
  12822. AbstractMesh.prototype._checkCollision = function (collider) {
  12823. // Bounding box test
  12824. if (!this._boundingInfo._checkCollision(collider))
  12825. return this;
  12826. // Transformation matrix
  12827. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12828. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12829. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12830. return this;
  12831. };
  12832. // Picking
  12833. AbstractMesh.prototype._generatePointsArray = function () {
  12834. return false;
  12835. };
  12836. /**
  12837. * Checks if the passed Ray intersects with the mesh.
  12838. * Returns an object PickingInfo.
  12839. */
  12840. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12841. var pickingInfo = new BABYLON.PickingInfo();
  12842. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12843. return pickingInfo;
  12844. }
  12845. if (!this._generatePointsArray()) {
  12846. return pickingInfo;
  12847. }
  12848. var intersectInfo = null;
  12849. // Octrees
  12850. var subMeshes;
  12851. var len;
  12852. if (this._submeshesOctree && this.useOctreeForPicking) {
  12853. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12854. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12855. len = intersections.length;
  12856. subMeshes = intersections.data;
  12857. }
  12858. else {
  12859. subMeshes = this.subMeshes;
  12860. len = subMeshes.length;
  12861. }
  12862. for (var index = 0; index < len; index++) {
  12863. var subMesh = subMeshes[index];
  12864. // Bounding test
  12865. if (len > 1 && !subMesh.canIntersects(ray))
  12866. continue;
  12867. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12868. if (currentIntersectInfo) {
  12869. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12870. intersectInfo = currentIntersectInfo;
  12871. intersectInfo.subMeshId = index;
  12872. if (fastCheck) {
  12873. break;
  12874. }
  12875. }
  12876. }
  12877. }
  12878. if (intersectInfo) {
  12879. // Get picked point
  12880. var world = this.getWorldMatrix();
  12881. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12882. var direction = ray.direction.clone();
  12883. direction = direction.scale(intersectInfo.distance);
  12884. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12885. var pickedPoint = worldOrigin.add(worldDirection);
  12886. // Return result
  12887. pickingInfo.hit = true;
  12888. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12889. pickingInfo.pickedPoint = pickedPoint;
  12890. pickingInfo.pickedMesh = this;
  12891. pickingInfo.bu = intersectInfo.bu;
  12892. pickingInfo.bv = intersectInfo.bv;
  12893. pickingInfo.faceId = intersectInfo.faceId;
  12894. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12895. return pickingInfo;
  12896. }
  12897. return pickingInfo;
  12898. };
  12899. /**
  12900. * Clones the mesh, used by the class Mesh.
  12901. * Just returns `null` for an AbstractMesh.
  12902. */
  12903. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12904. return null;
  12905. };
  12906. /**
  12907. * Disposes all the mesh submeshes.
  12908. * Returns the AbstractMesh.
  12909. */
  12910. AbstractMesh.prototype.releaseSubMeshes = function () {
  12911. if (this.subMeshes) {
  12912. while (this.subMeshes.length) {
  12913. this.subMeshes[0].dispose();
  12914. }
  12915. }
  12916. else {
  12917. this.subMeshes = new Array();
  12918. }
  12919. return this;
  12920. };
  12921. /**
  12922. * Disposes the AbstractMesh.
  12923. * Some internal references are kept for further use.
  12924. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12925. * Returns nothing.
  12926. */
  12927. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12928. var _this = this;
  12929. var index;
  12930. // Action manager
  12931. if (this.actionManager) {
  12932. this.actionManager.dispose();
  12933. this.actionManager = null;
  12934. }
  12935. // Skeleton
  12936. this.skeleton = null;
  12937. // Animations
  12938. this.getScene().stopAnimation(this);
  12939. // Physics
  12940. if (this.physicsImpostor) {
  12941. this.physicsImpostor.dispose();
  12942. }
  12943. // Intersections in progress
  12944. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12945. var other = this._intersectionsInProgress[index];
  12946. var pos = other._intersectionsInProgress.indexOf(this);
  12947. other._intersectionsInProgress.splice(pos, 1);
  12948. }
  12949. this._intersectionsInProgress = [];
  12950. // Lights
  12951. var lights = this.getScene().lights;
  12952. lights.forEach(function (light) {
  12953. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12954. if (meshIndex !== -1) {
  12955. light.includedOnlyMeshes.splice(meshIndex, 1);
  12956. }
  12957. meshIndex = light.excludedMeshes.indexOf(_this);
  12958. if (meshIndex !== -1) {
  12959. light.excludedMeshes.splice(meshIndex, 1);
  12960. }
  12961. // Shadow generators
  12962. var generator = light.getShadowGenerator();
  12963. if (generator) {
  12964. var shadowMap = generator.getShadowMap();
  12965. meshIndex = shadowMap.renderList.indexOf(_this);
  12966. if (meshIndex !== -1) {
  12967. shadowMap.renderList.splice(meshIndex, 1);
  12968. }
  12969. }
  12970. });
  12971. // Edges
  12972. if (this._edgesRenderer) {
  12973. this._edgesRenderer.dispose();
  12974. this._edgesRenderer = null;
  12975. }
  12976. // SubMeshes
  12977. if (this.getClassName() !== "InstancedMesh") {
  12978. this.releaseSubMeshes();
  12979. }
  12980. // Octree
  12981. var sceneOctree = this.getScene().selectionOctree;
  12982. if (sceneOctree) {
  12983. var index = sceneOctree.dynamicContent.indexOf(this);
  12984. if (index !== -1) {
  12985. sceneOctree.dynamicContent.splice(index, 1);
  12986. }
  12987. }
  12988. // Engine
  12989. this.getScene().getEngine().wipeCaches();
  12990. // Remove from scene
  12991. this.getScene().removeMesh(this);
  12992. if (!doNotRecurse) {
  12993. // Particles
  12994. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12995. if (this.getScene().particleSystems[index].emitter === this) {
  12996. this.getScene().particleSystems[index].dispose();
  12997. index--;
  12998. }
  12999. }
  13000. // Children
  13001. var objects = this.getDescendants(true);
  13002. for (index = 0; index < objects.length; index++) {
  13003. objects[index].dispose();
  13004. }
  13005. }
  13006. else {
  13007. var childMeshes = this.getChildMeshes(true);
  13008. for (index = 0; index < childMeshes.length; index++) {
  13009. var child = childMeshes[index];
  13010. child.parent = null;
  13011. child.computeWorldMatrix(true);
  13012. }
  13013. }
  13014. // facet data
  13015. if (this._facetDataEnabled) {
  13016. this.disableFacetData();
  13017. }
  13018. this.onAfterWorldMatrixUpdateObservable.clear();
  13019. this.onCollideObservable.clear();
  13020. this.onCollisionPositionChangeObservable.clear();
  13021. this._isDisposed = true;
  13022. _super.prototype.dispose.call(this);
  13023. };
  13024. /**
  13025. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13026. * This Vector3 is expressed in the World space.
  13027. */
  13028. AbstractMesh.prototype.getDirection = function (localAxis) {
  13029. var result = BABYLON.Vector3.Zero();
  13030. this.getDirectionToRef(localAxis, result);
  13031. return result;
  13032. };
  13033. /**
  13034. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13035. * localAxis is expressed in the mesh local space.
  13036. * result is computed in the Wordl space from the mesh World matrix.
  13037. * Returns the AbstractMesh.
  13038. */
  13039. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13040. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13041. return this;
  13042. };
  13043. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13044. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13045. if (this.getScene().getRenderId() == 0) {
  13046. this.computeWorldMatrix(true);
  13047. }
  13048. var wm = this.getWorldMatrix();
  13049. if (space == BABYLON.Space.WORLD) {
  13050. var tmat = BABYLON.Tmp.Matrix[0];
  13051. wm.invertToRef(tmat);
  13052. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13053. }
  13054. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13055. this._pivotMatrix.m[12] = -point.x;
  13056. this._pivotMatrix.m[13] = -point.y;
  13057. this._pivotMatrix.m[14] = -point.z;
  13058. this._cache.pivotMatrixUpdated = true;
  13059. return this;
  13060. };
  13061. /**
  13062. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13063. */
  13064. AbstractMesh.prototype.getPivotPoint = function () {
  13065. var point = BABYLON.Vector3.Zero();
  13066. this.getPivotPointToRef(point);
  13067. return point;
  13068. };
  13069. /**
  13070. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13071. * Returns the AbstractMesh.
  13072. */
  13073. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13074. result.x = -this._pivotMatrix.m[12];
  13075. result.y = -this._pivotMatrix.m[13];
  13076. result.z = -this._pivotMatrix.m[14];
  13077. return this;
  13078. };
  13079. /**
  13080. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13081. */
  13082. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13083. var point = BABYLON.Vector3.Zero();
  13084. this.getAbsolutePivotPointToRef(point);
  13085. return point;
  13086. };
  13087. /**
  13088. * Defines the passed mesh as the parent of the current mesh.
  13089. * Returns the AbstractMesh.
  13090. */
  13091. AbstractMesh.prototype.setParent = function (mesh) {
  13092. var child = this;
  13093. var parent = mesh;
  13094. if (mesh == null) {
  13095. var rotation = BABYLON.Tmp.Quaternion[0];
  13096. var position = BABYLON.Tmp.Vector3[0];
  13097. var scale = BABYLON.Tmp.Vector3[1];
  13098. child.getWorldMatrix().decompose(scale, rotation, position);
  13099. if (child.rotationQuaternion) {
  13100. child.rotationQuaternion.copyFrom(rotation);
  13101. }
  13102. else {
  13103. rotation.toEulerAnglesToRef(child.rotation);
  13104. }
  13105. child.position.x = position.x;
  13106. child.position.y = position.y;
  13107. child.position.z = position.z;
  13108. }
  13109. else {
  13110. var rotation = BABYLON.Tmp.Quaternion[0];
  13111. var position = BABYLON.Tmp.Vector3[0];
  13112. var scale = BABYLON.Tmp.Vector3[1];
  13113. var m1 = BABYLON.Tmp.Matrix[0];
  13114. var m2 = BABYLON.Tmp.Matrix[1];
  13115. parent.getWorldMatrix().decompose(scale, rotation, position);
  13116. rotation.toRotationMatrix(m1);
  13117. m2.setTranslation(position);
  13118. m2.multiplyToRef(m1, m1);
  13119. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13120. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13121. m.decompose(scale, rotation, position);
  13122. if (child.rotationQuaternion) {
  13123. child.rotationQuaternion.copyFrom(rotation);
  13124. }
  13125. else {
  13126. rotation.toEulerAnglesToRef(child.rotation);
  13127. }
  13128. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13129. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13130. m.decompose(scale, rotation, position);
  13131. child.position.x = position.x;
  13132. child.position.y = position.y;
  13133. child.position.z = position.z;
  13134. }
  13135. child.parent = parent;
  13136. return this;
  13137. };
  13138. /**
  13139. * Adds the passed mesh as a child to the current mesh.
  13140. * Returns the AbstractMesh.
  13141. */
  13142. AbstractMesh.prototype.addChild = function (mesh) {
  13143. mesh.setParent(this);
  13144. return this;
  13145. };
  13146. /**
  13147. * Removes the passed mesh from the current mesh children list.
  13148. * Returns the AbstractMesh.
  13149. */
  13150. AbstractMesh.prototype.removeChild = function (mesh) {
  13151. mesh.setParent(null);
  13152. return this;
  13153. };
  13154. /**
  13155. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13156. * Returns the AbstractMesh.
  13157. */
  13158. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13159. result.x = this._pivotMatrix.m[12];
  13160. result.y = this._pivotMatrix.m[13];
  13161. result.z = this._pivotMatrix.m[14];
  13162. this.getPivotPointToRef(result);
  13163. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13164. return this;
  13165. };
  13166. // Facet data
  13167. /**
  13168. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13169. * Returns the AbstractMesh.
  13170. */
  13171. AbstractMesh.prototype._initFacetData = function () {
  13172. if (!this._facetNormals) {
  13173. this._facetNormals = new Array();
  13174. }
  13175. if (!this._facetPositions) {
  13176. this._facetPositions = new Array();
  13177. }
  13178. if (!this._facetPartitioning) {
  13179. this._facetPartitioning = new Array();
  13180. }
  13181. this._facetNb = this.getIndices().length / 3;
  13182. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13183. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13184. for (var f = 0; f < this._facetNb; f++) {
  13185. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13186. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13187. }
  13188. this._facetDataEnabled = true;
  13189. return this;
  13190. };
  13191. /**
  13192. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13193. * This method can be called within the render loop.
  13194. * 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.
  13195. * Returns the AbstractMesh.
  13196. */
  13197. AbstractMesh.prototype.updateFacetData = function () {
  13198. if (!this._facetDataEnabled) {
  13199. this._initFacetData();
  13200. }
  13201. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13202. var indices = this.getIndices();
  13203. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13204. var bInfo = this.getBoundingInfo();
  13205. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13206. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13207. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13208. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13209. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13210. this._subDiv.max = this._partitioningSubdivisions;
  13211. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13212. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13213. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13214. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13215. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13216. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13217. // set the parameters for ComputeNormals()
  13218. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13219. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13220. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13221. this._facetParameters.bInfo = bInfo;
  13222. this._facetParameters.bbSize = this._bbSize;
  13223. this._facetParameters.subDiv = this._subDiv;
  13224. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13225. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13226. return this;
  13227. };
  13228. /**
  13229. * Returns the facetLocalNormals array.
  13230. * The normals are expressed in the mesh local space.
  13231. */
  13232. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13233. if (!this._facetNormals) {
  13234. this.updateFacetData();
  13235. }
  13236. return this._facetNormals;
  13237. };
  13238. /**
  13239. * Returns the facetLocalPositions array.
  13240. * The facet positions are expressed in the mesh local space.
  13241. */
  13242. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13243. if (!this._facetPositions) {
  13244. this.updateFacetData();
  13245. }
  13246. return this._facetPositions;
  13247. };
  13248. /**
  13249. * Returns the facetLocalPartioning array.
  13250. */
  13251. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13252. if (!this._facetPartitioning) {
  13253. this.updateFacetData();
  13254. }
  13255. return this._facetPartitioning;
  13256. };
  13257. /**
  13258. * Returns the i-th facet position in the world system.
  13259. * This method allocates a new Vector3 per call.
  13260. */
  13261. AbstractMesh.prototype.getFacetPosition = function (i) {
  13262. var pos = BABYLON.Vector3.Zero();
  13263. this.getFacetPositionToRef(i, pos);
  13264. return pos;
  13265. };
  13266. /**
  13267. * Sets the reference Vector3 with the i-th facet position in the world system.
  13268. * Returns the AbstractMesh.
  13269. */
  13270. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13271. var localPos = (this.getFacetLocalPositions())[i];
  13272. var world = this.getWorldMatrix();
  13273. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13274. return this;
  13275. };
  13276. /**
  13277. * Returns the i-th facet normal in the world system.
  13278. * This method allocates a new Vector3 per call.
  13279. */
  13280. AbstractMesh.prototype.getFacetNormal = function (i) {
  13281. var norm = BABYLON.Vector3.Zero();
  13282. this.getFacetNormalToRef(i, norm);
  13283. return norm;
  13284. };
  13285. /**
  13286. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13287. * Returns the AbstractMesh.
  13288. */
  13289. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13290. var localNorm = (this.getFacetLocalNormals())[i];
  13291. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13292. return this;
  13293. };
  13294. /**
  13295. * 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).
  13296. */
  13297. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13298. var bInfo = this.getBoundingInfo();
  13299. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13300. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13301. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13302. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13303. return null;
  13304. }
  13305. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13306. };
  13307. /**
  13308. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13309. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13310. * 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.
  13311. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13312. * 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.
  13313. */
  13314. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13315. if (checkFace === void 0) { checkFace = false; }
  13316. if (facing === void 0) { facing = true; }
  13317. var world = this.getWorldMatrix();
  13318. var invMat = BABYLON.Tmp.Matrix[5];
  13319. world.invertToRef(invMat);
  13320. var invVect = BABYLON.Tmp.Vector3[8];
  13321. var closest = null;
  13322. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13323. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13324. if (projected) {
  13325. // tranform the local computed projected vector to world coordinates
  13326. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13327. }
  13328. return closest;
  13329. };
  13330. /**
  13331. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13332. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13333. * 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.
  13334. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13335. * 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.
  13336. */
  13337. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13338. if (checkFace === void 0) { checkFace = false; }
  13339. if (facing === void 0) { facing = true; }
  13340. var closest = null;
  13341. var tmpx = 0.0;
  13342. var tmpy = 0.0;
  13343. var tmpz = 0.0;
  13344. var d = 0.0; // tmp dot facet normal * facet position
  13345. var t0 = 0.0;
  13346. var projx = 0.0;
  13347. var projy = 0.0;
  13348. var projz = 0.0;
  13349. // Get all the facets in the same partitioning block than (x, y, z)
  13350. var facetPositions = this.getFacetLocalPositions();
  13351. var facetNormals = this.getFacetLocalNormals();
  13352. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13353. if (!facetsInBlock) {
  13354. return null;
  13355. }
  13356. // Get the closest facet to (x, y, z)
  13357. var shortest = Number.MAX_VALUE; // init distance vars
  13358. var tmpDistance = shortest;
  13359. var fib; // current facet in the block
  13360. var norm; // current facet normal
  13361. var p0; // current facet barycenter position
  13362. // loop on all the facets in the current partitioning block
  13363. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13364. fib = facetsInBlock[idx];
  13365. norm = facetNormals[fib];
  13366. p0 = facetPositions[fib];
  13367. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13368. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13369. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13370. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13371. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13372. projx = x + norm.x * t0;
  13373. projy = y + norm.y * t0;
  13374. projz = z + norm.z * t0;
  13375. tmpx = projx - x;
  13376. tmpy = projy - y;
  13377. tmpz = projz - z;
  13378. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13379. if (tmpDistance < shortest) {
  13380. shortest = tmpDistance;
  13381. closest = fib;
  13382. if (projected) {
  13383. projected.x = projx;
  13384. projected.y = projy;
  13385. projected.z = projz;
  13386. }
  13387. }
  13388. }
  13389. }
  13390. return closest;
  13391. };
  13392. /**
  13393. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13394. */
  13395. AbstractMesh.prototype.getFacetDataParameters = function () {
  13396. return this._facetParameters;
  13397. };
  13398. /**
  13399. * Disables the feature FacetData and frees the related memory.
  13400. * Returns the AbstractMesh.
  13401. */
  13402. AbstractMesh.prototype.disableFacetData = function () {
  13403. if (this._facetDataEnabled) {
  13404. this._facetDataEnabled = false;
  13405. this._facetPositions = null;
  13406. this._facetNormals = null;
  13407. this._facetPartitioning = null;
  13408. this._facetParameters = null;
  13409. }
  13410. return this;
  13411. };
  13412. /**
  13413. * Creates new normals data for the mesh.
  13414. * @param updatable.
  13415. */
  13416. AbstractMesh.prototype.createNormals = function (updatable) {
  13417. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13418. var indices = this.getIndices();
  13419. var normals;
  13420. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13421. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13422. }
  13423. else {
  13424. normals = [];
  13425. }
  13426. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13427. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13428. };
  13429. return AbstractMesh;
  13430. }(BABYLON.Node));
  13431. // Statics
  13432. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13433. AbstractMesh._BILLBOARDMODE_X = 1;
  13434. AbstractMesh._BILLBOARDMODE_Y = 2;
  13435. AbstractMesh._BILLBOARDMODE_Z = 4;
  13436. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13437. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13438. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13439. BABYLON.AbstractMesh = AbstractMesh;
  13440. })(BABYLON || (BABYLON = {}));
  13441. //# sourceMappingURL=babylon.abstractMesh.js.map
  13442. var BABYLON;
  13443. (function (BABYLON) {
  13444. var Light = (function (_super) {
  13445. __extends(Light, _super);
  13446. /**
  13447. * Creates a Light object in the scene.
  13448. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13449. */
  13450. function Light(name, scene) {
  13451. var _this = _super.call(this, name, scene) || this;
  13452. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13453. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13454. _this.intensity = 1.0;
  13455. _this.range = Number.MAX_VALUE;
  13456. /**
  13457. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13458. * of light.
  13459. */
  13460. _this._photometricScale = 1.0;
  13461. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13462. _this._radius = 0.00001;
  13463. _this.renderPriority = 0;
  13464. /**
  13465. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13466. * the current shadow generator.
  13467. */
  13468. _this.shadowEnabled = true;
  13469. _this._excludeWithLayerMask = 0;
  13470. _this._includeOnlyWithLayerMask = 0;
  13471. _this._lightmapMode = 0;
  13472. _this._excludedMeshesIds = new Array();
  13473. _this._includedOnlyMeshesIds = new Array();
  13474. _this.getScene().addLight(_this);
  13475. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13476. _this._buildUniformLayout();
  13477. _this.includedOnlyMeshes = new Array();
  13478. _this.excludedMeshes = new Array();
  13479. _this._resyncMeshes();
  13480. return _this;
  13481. }
  13482. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13483. /**
  13484. * If every light affecting the material is in this lightmapMode,
  13485. * material.lightmapTexture adds or multiplies
  13486. * (depends on material.useLightmapAsShadowmap)
  13487. * after every other light calculations.
  13488. */
  13489. get: function () {
  13490. return Light._LIGHTMAP_DEFAULT;
  13491. },
  13492. enumerable: true,
  13493. configurable: true
  13494. });
  13495. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13496. /**
  13497. * material.lightmapTexture as only diffuse lighting from this light
  13498. * adds pnly specular lighting from this light
  13499. * adds dynamic shadows
  13500. */
  13501. get: function () {
  13502. return Light._LIGHTMAP_SPECULAR;
  13503. },
  13504. enumerable: true,
  13505. configurable: true
  13506. });
  13507. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13508. /**
  13509. * material.lightmapTexture as only lighting
  13510. * no light calculation from this light
  13511. * only adds dynamic shadows from this light
  13512. */
  13513. get: function () {
  13514. return Light._LIGHTMAP_SHADOWSONLY;
  13515. },
  13516. enumerable: true,
  13517. configurable: true
  13518. });
  13519. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13520. /**
  13521. * Each light type uses the default quantity according to its type:
  13522. * point/spot lights use luminous intensity
  13523. * directional lights use illuminance
  13524. */
  13525. get: function () {
  13526. return Light._INTENSITYMODE_AUTOMATIC;
  13527. },
  13528. enumerable: true,
  13529. configurable: true
  13530. });
  13531. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13532. /**
  13533. * lumen (lm)
  13534. */
  13535. get: function () {
  13536. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13537. },
  13538. enumerable: true,
  13539. configurable: true
  13540. });
  13541. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13542. /**
  13543. * candela (lm/sr)
  13544. */
  13545. get: function () {
  13546. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13547. },
  13548. enumerable: true,
  13549. configurable: true
  13550. });
  13551. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13552. /**
  13553. * lux (lm/m^2)
  13554. */
  13555. get: function () {
  13556. return Light._INTENSITYMODE_ILLUMINANCE;
  13557. },
  13558. enumerable: true,
  13559. configurable: true
  13560. });
  13561. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13562. /**
  13563. * nit (cd/m^2)
  13564. */
  13565. get: function () {
  13566. return Light._INTENSITYMODE_LUMINANCE;
  13567. },
  13568. enumerable: true,
  13569. configurable: true
  13570. });
  13571. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13572. /**
  13573. * Light type const id of the point light.
  13574. */
  13575. get: function () {
  13576. return Light._LIGHTTYPEID_POINTLIGHT;
  13577. },
  13578. enumerable: true,
  13579. configurable: true
  13580. });
  13581. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13582. /**
  13583. * Light type const id of the directional light.
  13584. */
  13585. get: function () {
  13586. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13587. },
  13588. enumerable: true,
  13589. configurable: true
  13590. });
  13591. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13592. /**
  13593. * Light type const id of the spot light.
  13594. */
  13595. get: function () {
  13596. return Light._LIGHTTYPEID_SPOTLIGHT;
  13597. },
  13598. enumerable: true,
  13599. configurable: true
  13600. });
  13601. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13602. /**
  13603. * Light type const id of the hemispheric light.
  13604. */
  13605. get: function () {
  13606. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13607. },
  13608. enumerable: true,
  13609. configurable: true
  13610. });
  13611. Object.defineProperty(Light.prototype, "intensityMode", {
  13612. /**
  13613. * Gets the photometric scale used to interpret the intensity.
  13614. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13615. */
  13616. get: function () {
  13617. return this._intensityMode;
  13618. },
  13619. /**
  13620. * Sets the photometric scale used to interpret the intensity.
  13621. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13622. */
  13623. set: function (value) {
  13624. this._intensityMode = value;
  13625. this._computePhotometricScale();
  13626. },
  13627. enumerable: true,
  13628. configurable: true
  13629. });
  13630. ;
  13631. ;
  13632. Object.defineProperty(Light.prototype, "radius", {
  13633. /**
  13634. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13635. */
  13636. get: function () {
  13637. return this._radius;
  13638. },
  13639. /**
  13640. * sets the light radius used by PBR Materials to simulate soft area lights.
  13641. */
  13642. set: function (value) {
  13643. this._radius = value;
  13644. this._computePhotometricScale();
  13645. },
  13646. enumerable: true,
  13647. configurable: true
  13648. });
  13649. ;
  13650. ;
  13651. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13652. get: function () {
  13653. return this._includedOnlyMeshes;
  13654. },
  13655. set: function (value) {
  13656. this._includedOnlyMeshes = value;
  13657. this._hookArrayForIncludedOnly(value);
  13658. },
  13659. enumerable: true,
  13660. configurable: true
  13661. });
  13662. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13663. get: function () {
  13664. return this._excludedMeshes;
  13665. },
  13666. set: function (value) {
  13667. this._excludedMeshes = value;
  13668. this._hookArrayForExcluded(value);
  13669. },
  13670. enumerable: true,
  13671. configurable: true
  13672. });
  13673. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13674. get: function () {
  13675. return this._excludeWithLayerMask;
  13676. },
  13677. set: function (value) {
  13678. this._excludeWithLayerMask = value;
  13679. this._resyncMeshes();
  13680. },
  13681. enumerable: true,
  13682. configurable: true
  13683. });
  13684. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13685. get: function () {
  13686. return this._includeOnlyWithLayerMask;
  13687. },
  13688. set: function (value) {
  13689. this._includeOnlyWithLayerMask = value;
  13690. this._resyncMeshes();
  13691. },
  13692. enumerable: true,
  13693. configurable: true
  13694. });
  13695. Object.defineProperty(Light.prototype, "lightmapMode", {
  13696. get: function () {
  13697. return this._lightmapMode;
  13698. },
  13699. set: function (value) {
  13700. if (this._lightmapMode === value) {
  13701. return;
  13702. }
  13703. this._lightmapMode = value;
  13704. this._markMeshesAsLightDirty();
  13705. },
  13706. enumerable: true,
  13707. configurable: true
  13708. });
  13709. Light.prototype._buildUniformLayout = function () {
  13710. // Overridden
  13711. };
  13712. /**
  13713. * Returns the string "Light".
  13714. */
  13715. Light.prototype.getClassName = function () {
  13716. return "Light";
  13717. };
  13718. /**
  13719. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13720. */
  13721. Light.prototype.toString = function (fullDetails) {
  13722. var ret = "Name: " + this.name;
  13723. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13724. if (this.animations) {
  13725. for (var i = 0; i < this.animations.length; i++) {
  13726. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13727. }
  13728. }
  13729. if (fullDetails) {
  13730. }
  13731. return ret;
  13732. };
  13733. /**
  13734. * Set the enabled state of this node.
  13735. * @param {boolean} value - the new enabled state
  13736. * @see isEnabled
  13737. */
  13738. Light.prototype.setEnabled = function (value) {
  13739. _super.prototype.setEnabled.call(this, value);
  13740. this._resyncMeshes();
  13741. };
  13742. /**
  13743. * Returns the Light associated shadow generator.
  13744. */
  13745. Light.prototype.getShadowGenerator = function () {
  13746. return this._shadowGenerator;
  13747. };
  13748. /**
  13749. * Returns a Vector3, the absolute light position in the World.
  13750. */
  13751. Light.prototype.getAbsolutePosition = function () {
  13752. return BABYLON.Vector3.Zero();
  13753. };
  13754. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13755. };
  13756. Light.prototype._getWorldMatrix = function () {
  13757. return BABYLON.Matrix.Identity();
  13758. };
  13759. /**
  13760. * Boolean : True if the light will affect the passed mesh.
  13761. */
  13762. Light.prototype.canAffectMesh = function (mesh) {
  13763. if (!mesh) {
  13764. return true;
  13765. }
  13766. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13767. return false;
  13768. }
  13769. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13770. return false;
  13771. }
  13772. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13773. return false;
  13774. }
  13775. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13776. return false;
  13777. }
  13778. return true;
  13779. };
  13780. /**
  13781. * Returns the light World matrix.
  13782. */
  13783. Light.prototype.getWorldMatrix = function () {
  13784. this._currentRenderId = this.getScene().getRenderId();
  13785. var worldMatrix = this._getWorldMatrix();
  13786. if (this.parent && this.parent.getWorldMatrix) {
  13787. if (!this._parentedWorldMatrix) {
  13788. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13789. }
  13790. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13791. this._markSyncedWithParent();
  13792. return this._parentedWorldMatrix;
  13793. }
  13794. return worldMatrix;
  13795. };
  13796. /**
  13797. * Sort function to order lights for rendering.
  13798. * @param a First Light object to compare to second.
  13799. * @param b Second Light object to compare first.
  13800. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13801. */
  13802. Light.compareLightsPriority = function (a, b) {
  13803. //shadow-casting lights have priority over non-shadow-casting lights
  13804. //the renderPrioirty is a secondary sort criterion
  13805. if (a.shadowEnabled !== b.shadowEnabled) {
  13806. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13807. }
  13808. return b.renderPriority - a.renderPriority;
  13809. };
  13810. /**
  13811. * Disposes the light.
  13812. */
  13813. Light.prototype.dispose = function () {
  13814. if (this._shadowGenerator) {
  13815. this._shadowGenerator.dispose();
  13816. this._shadowGenerator = null;
  13817. }
  13818. // Animations
  13819. this.getScene().stopAnimation(this);
  13820. // Remove from meshes
  13821. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13822. var mesh = _a[_i];
  13823. mesh._removeLightSource(this);
  13824. }
  13825. this._uniformBuffer.dispose();
  13826. // Remove from scene
  13827. this.getScene().removeLight(this);
  13828. _super.prototype.dispose.call(this);
  13829. };
  13830. /**
  13831. * Returns the light type ID (integer).
  13832. */
  13833. Light.prototype.getTypeID = function () {
  13834. return 0;
  13835. };
  13836. /**
  13837. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13838. */
  13839. Light.prototype.getScaledIntensity = function () {
  13840. return this._photometricScale * this.intensity;
  13841. };
  13842. /**
  13843. * Returns a new Light object, named "name", from the current one.
  13844. */
  13845. Light.prototype.clone = function (name) {
  13846. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13847. };
  13848. /**
  13849. * Serializes the current light into a Serialization object.
  13850. * Returns the serialized object.
  13851. */
  13852. Light.prototype.serialize = function () {
  13853. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13854. // Type
  13855. serializationObject.type = this.getTypeID();
  13856. // Parent
  13857. if (this.parent) {
  13858. serializationObject.parentId = this.parent.id;
  13859. }
  13860. // Inclusion / exclusions
  13861. if (this.excludedMeshes.length > 0) {
  13862. serializationObject.excludedMeshesIds = [];
  13863. this.excludedMeshes.forEach(function (mesh) {
  13864. serializationObject.excludedMeshesIds.push(mesh.id);
  13865. });
  13866. }
  13867. if (this.includedOnlyMeshes.length > 0) {
  13868. serializationObject.includedOnlyMeshesIds = [];
  13869. this.includedOnlyMeshes.forEach(function (mesh) {
  13870. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13871. });
  13872. }
  13873. // Animations
  13874. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13875. serializationObject.ranges = this.serializeAnimationRanges();
  13876. return serializationObject;
  13877. };
  13878. /**
  13879. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13880. * This new light is named "name" and added to the passed scene.
  13881. */
  13882. Light.GetConstructorFromName = function (type, name, scene) {
  13883. switch (type) {
  13884. case 0:
  13885. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13886. case 1:
  13887. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13888. case 2:
  13889. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13890. case 3:
  13891. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13892. }
  13893. };
  13894. /**
  13895. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13896. */
  13897. Light.Parse = function (parsedLight, scene) {
  13898. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13899. // Inclusion / exclusions
  13900. if (parsedLight.excludedMeshesIds) {
  13901. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13902. }
  13903. if (parsedLight.includedOnlyMeshesIds) {
  13904. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13905. }
  13906. // Parent
  13907. if (parsedLight.parentId) {
  13908. light._waitingParentId = parsedLight.parentId;
  13909. }
  13910. // Animations
  13911. if (parsedLight.animations) {
  13912. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13913. var parsedAnimation = parsedLight.animations[animationIndex];
  13914. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13915. }
  13916. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13917. }
  13918. if (parsedLight.autoAnimate) {
  13919. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13920. }
  13921. return light;
  13922. };
  13923. Light.prototype._hookArrayForExcluded = function (array) {
  13924. var _this = this;
  13925. var oldPush = array.push;
  13926. array.push = function () {
  13927. var items = [];
  13928. for (var _i = 0; _i < arguments.length; _i++) {
  13929. items[_i] = arguments[_i];
  13930. }
  13931. var result = oldPush.apply(array, items);
  13932. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13933. var item = items_1[_a];
  13934. item._resyncLighSource(_this);
  13935. }
  13936. return result;
  13937. };
  13938. var oldSplice = array.splice;
  13939. array.splice = function (index, deleteCount) {
  13940. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13941. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13942. var item = deleted_1[_i];
  13943. item._resyncLighSource(_this);
  13944. }
  13945. return deleted;
  13946. };
  13947. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13948. var item = array_1[_i];
  13949. item._resyncLighSource(this);
  13950. }
  13951. };
  13952. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13953. var _this = this;
  13954. var oldPush = array.push;
  13955. array.push = function () {
  13956. var items = [];
  13957. for (var _i = 0; _i < arguments.length; _i++) {
  13958. items[_i] = arguments[_i];
  13959. }
  13960. var result = oldPush.apply(array, items);
  13961. _this._resyncMeshes();
  13962. return result;
  13963. };
  13964. var oldSplice = array.splice;
  13965. array.splice = function (index, deleteCount) {
  13966. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13967. _this._resyncMeshes();
  13968. return deleted;
  13969. };
  13970. this._resyncMeshes();
  13971. };
  13972. Light.prototype._resyncMeshes = function () {
  13973. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13974. var mesh = _a[_i];
  13975. mesh._resyncLighSource(this);
  13976. }
  13977. };
  13978. Light.prototype._markMeshesAsLightDirty = function () {
  13979. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13980. var mesh = _a[_i];
  13981. if (mesh._lightSources.indexOf(this) !== -1) {
  13982. mesh._markSubMeshesAsLightDirty();
  13983. }
  13984. }
  13985. };
  13986. /**
  13987. * Recomputes the cached photometric scale if needed.
  13988. */
  13989. Light.prototype._computePhotometricScale = function () {
  13990. this._photometricScale = this._getPhotometricScale();
  13991. this.getScene().resetCachedMaterial();
  13992. };
  13993. /**
  13994. * Returns the Photometric Scale according to the light type and intensity mode.
  13995. */
  13996. Light.prototype._getPhotometricScale = function () {
  13997. var photometricScale = 0.0;
  13998. var lightTypeID = this.getTypeID();
  13999. //get photometric mode
  14000. var photometricMode = this.intensityMode;
  14001. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14002. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14003. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14004. }
  14005. else {
  14006. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14007. }
  14008. }
  14009. //compute photometric scale
  14010. switch (lightTypeID) {
  14011. case Light.LIGHTTYPEID_POINTLIGHT:
  14012. case Light.LIGHTTYPEID_SPOTLIGHT:
  14013. switch (photometricMode) {
  14014. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14015. photometricScale = 1.0 / (4.0 * Math.PI);
  14016. break;
  14017. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14018. photometricScale = 1.0;
  14019. break;
  14020. case Light.INTENSITYMODE_LUMINANCE:
  14021. photometricScale = this.radius * this.radius;
  14022. break;
  14023. }
  14024. break;
  14025. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14026. switch (photometricMode) {
  14027. case Light.INTENSITYMODE_ILLUMINANCE:
  14028. photometricScale = 1.0;
  14029. break;
  14030. case Light.INTENSITYMODE_LUMINANCE:
  14031. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14032. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14033. var apexAngleRadians = this.radius;
  14034. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14035. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14036. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14037. photometricScale = solidAngle;
  14038. break;
  14039. }
  14040. break;
  14041. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14042. // No fall off in hemisperic light.
  14043. photometricScale = 1.0;
  14044. break;
  14045. }
  14046. return photometricScale;
  14047. };
  14048. Light.prototype._reorderLightsInScene = function () {
  14049. var scene = this.getScene();
  14050. if (this.renderPriority != 0) {
  14051. scene.requireLightSorting = true;
  14052. }
  14053. this.getScene().sortLightsByPriority();
  14054. };
  14055. return Light;
  14056. }(BABYLON.Node));
  14057. //lightmapMode Consts
  14058. Light._LIGHTMAP_DEFAULT = 0;
  14059. Light._LIGHTMAP_SPECULAR = 1;
  14060. Light._LIGHTMAP_SHADOWSONLY = 2;
  14061. // Intensity Mode Consts
  14062. Light._INTENSITYMODE_AUTOMATIC = 0;
  14063. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14064. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14065. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14066. Light._INTENSITYMODE_LUMINANCE = 4;
  14067. // Light types ids const.
  14068. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14069. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14070. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14071. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14072. __decorate([
  14073. BABYLON.serializeAsColor3()
  14074. ], Light.prototype, "diffuse", void 0);
  14075. __decorate([
  14076. BABYLON.serializeAsColor3()
  14077. ], Light.prototype, "specular", void 0);
  14078. __decorate([
  14079. BABYLON.serialize()
  14080. ], Light.prototype, "intensity", void 0);
  14081. __decorate([
  14082. BABYLON.serialize()
  14083. ], Light.prototype, "range", void 0);
  14084. __decorate([
  14085. BABYLON.serialize()
  14086. ], Light.prototype, "intensityMode", null);
  14087. __decorate([
  14088. BABYLON.serialize()
  14089. ], Light.prototype, "radius", null);
  14090. __decorate([
  14091. BABYLON.serialize()
  14092. ], Light.prototype, "_renderPriority", void 0);
  14093. __decorate([
  14094. BABYLON.expandToProperty("_reorderLightsInScene")
  14095. ], Light.prototype, "renderPriority", void 0);
  14096. __decorate([
  14097. BABYLON.serialize()
  14098. ], Light.prototype, "shadowEnabled", void 0);
  14099. __decorate([
  14100. BABYLON.serialize("excludeWithLayerMask")
  14101. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14102. __decorate([
  14103. BABYLON.serialize("includeOnlyWithLayerMask")
  14104. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14105. __decorate([
  14106. BABYLON.serialize("lightmapMode")
  14107. ], Light.prototype, "_lightmapMode", void 0);
  14108. BABYLON.Light = Light;
  14109. })(BABYLON || (BABYLON = {}));
  14110. //# sourceMappingURL=babylon.light.js.map
  14111. var BABYLON;
  14112. (function (BABYLON) {
  14113. var Camera = (function (_super) {
  14114. __extends(Camera, _super);
  14115. function Camera(name, position, scene) {
  14116. var _this = _super.call(this, name, scene) || this;
  14117. _this.upVector = BABYLON.Vector3.Up();
  14118. _this.orthoLeft = null;
  14119. _this.orthoRight = null;
  14120. _this.orthoBottom = null;
  14121. _this.orthoTop = null;
  14122. _this.fov = 0.8;
  14123. _this.minZ = 1.0;
  14124. _this.maxZ = 10000.0;
  14125. _this.inertia = 0.9;
  14126. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14127. _this.isIntermediate = false;
  14128. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14129. _this.layerMask = 0x0FFFFFFF;
  14130. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14131. // Camera rig members
  14132. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14133. _this._rigCameras = new Array();
  14134. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14135. _this.customRenderTargets = new Array();
  14136. // Cache
  14137. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14138. _this._projectionMatrix = new BABYLON.Matrix();
  14139. _this._doNotComputeProjectionMatrix = false;
  14140. _this._postProcesses = new Array();
  14141. _this._transformMatrix = BABYLON.Matrix.Zero();
  14142. _this._activeMeshes = new BABYLON.SmartArray(256);
  14143. _this._globalPosition = BABYLON.Vector3.Zero();
  14144. _this._refreshFrustumPlanes = true;
  14145. _this.getScene().addCamera(_this);
  14146. if (!_this.getScene().activeCamera) {
  14147. _this.getScene().activeCamera = _this;
  14148. }
  14149. _this.position = position;
  14150. return _this;
  14151. }
  14152. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14153. get: function () {
  14154. return Camera._PERSPECTIVE_CAMERA;
  14155. },
  14156. enumerable: true,
  14157. configurable: true
  14158. });
  14159. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14160. get: function () {
  14161. return Camera._ORTHOGRAPHIC_CAMERA;
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14167. get: function () {
  14168. return Camera._FOVMODE_VERTICAL_FIXED;
  14169. },
  14170. enumerable: true,
  14171. configurable: true
  14172. });
  14173. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14174. get: function () {
  14175. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14176. },
  14177. enumerable: true,
  14178. configurable: true
  14179. });
  14180. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14181. get: function () {
  14182. return Camera._RIG_MODE_NONE;
  14183. },
  14184. enumerable: true,
  14185. configurable: true
  14186. });
  14187. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14188. get: function () {
  14189. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14190. },
  14191. enumerable: true,
  14192. configurable: true
  14193. });
  14194. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14195. get: function () {
  14196. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14197. },
  14198. enumerable: true,
  14199. configurable: true
  14200. });
  14201. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14202. get: function () {
  14203. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14204. },
  14205. enumerable: true,
  14206. configurable: true
  14207. });
  14208. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14209. get: function () {
  14210. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14211. },
  14212. enumerable: true,
  14213. configurable: true
  14214. });
  14215. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14216. get: function () {
  14217. return Camera._RIG_MODE_VR;
  14218. },
  14219. enumerable: true,
  14220. configurable: true
  14221. });
  14222. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14223. get: function () {
  14224. return Camera._RIG_MODE_WEBVR;
  14225. },
  14226. enumerable: true,
  14227. configurable: true
  14228. });
  14229. Camera.prototype.getClassName = function () {
  14230. return "Camera";
  14231. };
  14232. /**
  14233. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14234. */
  14235. Camera.prototype.toString = function (fullDetails) {
  14236. var ret = "Name: " + this.name;
  14237. ret += ", type: " + this.getClassName();
  14238. if (this.animations) {
  14239. for (var i = 0; i < this.animations.length; i++) {
  14240. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14241. }
  14242. }
  14243. if (fullDetails) {
  14244. }
  14245. return ret;
  14246. };
  14247. Object.defineProperty(Camera.prototype, "globalPosition", {
  14248. get: function () {
  14249. return this._globalPosition;
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. Camera.prototype.getActiveMeshes = function () {
  14255. return this._activeMeshes;
  14256. };
  14257. Camera.prototype.isActiveMesh = function (mesh) {
  14258. return (this._activeMeshes.indexOf(mesh) !== -1);
  14259. };
  14260. //Cache
  14261. Camera.prototype._initCache = function () {
  14262. _super.prototype._initCache.call(this);
  14263. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14264. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14265. this._cache.mode = undefined;
  14266. this._cache.minZ = undefined;
  14267. this._cache.maxZ = undefined;
  14268. this._cache.fov = undefined;
  14269. this._cache.fovMode = undefined;
  14270. this._cache.aspectRatio = undefined;
  14271. this._cache.orthoLeft = undefined;
  14272. this._cache.orthoRight = undefined;
  14273. this._cache.orthoBottom = undefined;
  14274. this._cache.orthoTop = undefined;
  14275. this._cache.renderWidth = undefined;
  14276. this._cache.renderHeight = undefined;
  14277. };
  14278. Camera.prototype._updateCache = function (ignoreParentClass) {
  14279. if (!ignoreParentClass) {
  14280. _super.prototype._updateCache.call(this);
  14281. }
  14282. var engine = this.getEngine();
  14283. this._cache.position.copyFrom(this.position);
  14284. this._cache.upVector.copyFrom(this.upVector);
  14285. this._cache.mode = this.mode;
  14286. this._cache.minZ = this.minZ;
  14287. this._cache.maxZ = this.maxZ;
  14288. this._cache.fov = this.fov;
  14289. this._cache.fovMode = this.fovMode;
  14290. this._cache.aspectRatio = engine.getAspectRatio(this);
  14291. this._cache.orthoLeft = this.orthoLeft;
  14292. this._cache.orthoRight = this.orthoRight;
  14293. this._cache.orthoBottom = this.orthoBottom;
  14294. this._cache.orthoTop = this.orthoTop;
  14295. this._cache.renderWidth = engine.getRenderWidth();
  14296. this._cache.renderHeight = engine.getRenderHeight();
  14297. };
  14298. Camera.prototype._updateFromScene = function () {
  14299. this.updateCache();
  14300. this.update();
  14301. };
  14302. // Synchronized
  14303. Camera.prototype._isSynchronized = function () {
  14304. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14305. };
  14306. Camera.prototype._isSynchronizedViewMatrix = function () {
  14307. if (!_super.prototype._isSynchronized.call(this))
  14308. return false;
  14309. return this._cache.position.equals(this.position)
  14310. && this._cache.upVector.equals(this.upVector)
  14311. && this.isSynchronizedWithParent();
  14312. };
  14313. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14314. var check = this._cache.mode === this.mode
  14315. && this._cache.minZ === this.minZ
  14316. && this._cache.maxZ === this.maxZ;
  14317. if (!check) {
  14318. return false;
  14319. }
  14320. var engine = this.getEngine();
  14321. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14322. check = this._cache.fov === this.fov
  14323. && this._cache.fovMode === this.fovMode
  14324. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14325. }
  14326. else {
  14327. check = this._cache.orthoLeft === this.orthoLeft
  14328. && this._cache.orthoRight === this.orthoRight
  14329. && this._cache.orthoBottom === this.orthoBottom
  14330. && this._cache.orthoTop === this.orthoTop
  14331. && this._cache.renderWidth === engine.getRenderWidth()
  14332. && this._cache.renderHeight === engine.getRenderHeight();
  14333. }
  14334. return check;
  14335. };
  14336. // Controls
  14337. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14338. };
  14339. Camera.prototype.detachControl = function (element) {
  14340. };
  14341. Camera.prototype.update = function () {
  14342. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14343. this._updateRigCameras();
  14344. }
  14345. this._checkInputs();
  14346. };
  14347. Camera.prototype._checkInputs = function () {
  14348. };
  14349. Object.defineProperty(Camera.prototype, "rigCameras", {
  14350. get: function () {
  14351. return this._rigCameras;
  14352. },
  14353. enumerable: true,
  14354. configurable: true
  14355. });
  14356. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14357. get: function () {
  14358. return this._rigPostProcess;
  14359. },
  14360. enumerable: true,
  14361. configurable: true
  14362. });
  14363. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14364. // invalidate framebuffer
  14365. if (this._postProcesses.length > 0) {
  14366. this._postProcesses[0].markTextureDirty();
  14367. }
  14368. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14369. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14370. var cam = this._rigCameras[i];
  14371. var rigPostProcess = cam._rigPostProcess;
  14372. // for VR rig, there does not have to be a post process
  14373. if (rigPostProcess) {
  14374. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14375. if (isPass) {
  14376. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14377. cam.isIntermediate = this._postProcesses.length === 0;
  14378. }
  14379. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14380. rigPostProcess.markTextureDirty();
  14381. }
  14382. else {
  14383. cam._postProcesses = this._postProcesses.slice(0);
  14384. }
  14385. }
  14386. };
  14387. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14388. if (insertAt === void 0) { insertAt = null; }
  14389. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14390. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14391. return 0;
  14392. }
  14393. if (insertAt == null || insertAt < 0) {
  14394. this._postProcesses.push(postProcess);
  14395. }
  14396. else {
  14397. this._postProcesses.splice(insertAt, 0, postProcess);
  14398. }
  14399. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14400. return this._postProcesses.indexOf(postProcess);
  14401. };
  14402. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14403. if (atIndices === void 0) { atIndices = null; }
  14404. var result = [];
  14405. var i;
  14406. var index;
  14407. if (!atIndices) {
  14408. var idx = this._postProcesses.indexOf(postProcess);
  14409. if (idx !== -1) {
  14410. this._postProcesses.splice(idx, 1);
  14411. }
  14412. }
  14413. else {
  14414. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14415. // iterate descending, so can just splice as we go
  14416. for (i = atIndices.length - 1; i >= 0; i--) {
  14417. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14418. result.push(i);
  14419. continue;
  14420. }
  14421. index = atIndices[i];
  14422. this._postProcesses.splice(index, 1);
  14423. }
  14424. }
  14425. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14426. return result;
  14427. };
  14428. Camera.prototype.getWorldMatrix = function () {
  14429. if (!this._worldMatrix) {
  14430. this._worldMatrix = BABYLON.Matrix.Identity();
  14431. }
  14432. var viewMatrix = this.getViewMatrix();
  14433. viewMatrix.invertToRef(this._worldMatrix);
  14434. return this._worldMatrix;
  14435. };
  14436. Camera.prototype._getViewMatrix = function () {
  14437. return BABYLON.Matrix.Identity();
  14438. };
  14439. Camera.prototype.getViewMatrix = function (force) {
  14440. this._computedViewMatrix = this._computeViewMatrix(force);
  14441. if (!force && this._isSynchronizedViewMatrix()) {
  14442. return this._computedViewMatrix;
  14443. }
  14444. this._refreshFrustumPlanes = true;
  14445. if (!this.parent || !this.parent.getWorldMatrix) {
  14446. this._globalPosition.copyFrom(this.position);
  14447. }
  14448. else {
  14449. if (!this._worldMatrix) {
  14450. this._worldMatrix = BABYLON.Matrix.Identity();
  14451. }
  14452. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14453. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14454. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14455. this._computedViewMatrix.invert();
  14456. this._markSyncedWithParent();
  14457. }
  14458. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14459. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14460. }
  14461. this._currentRenderId = this.getScene().getRenderId();
  14462. return this._computedViewMatrix;
  14463. };
  14464. Camera.prototype._computeViewMatrix = function (force) {
  14465. if (!force && this._isSynchronizedViewMatrix()) {
  14466. return this._computedViewMatrix;
  14467. }
  14468. this._computedViewMatrix = this._getViewMatrix();
  14469. this._currentRenderId = this.getScene().getRenderId();
  14470. return this._computedViewMatrix;
  14471. };
  14472. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14473. this._doNotComputeProjectionMatrix = true;
  14474. if (projection !== undefined) {
  14475. this._projectionMatrix = projection;
  14476. }
  14477. };
  14478. ;
  14479. Camera.prototype.unfreezeProjectionMatrix = function () {
  14480. this._doNotComputeProjectionMatrix = false;
  14481. };
  14482. ;
  14483. Camera.prototype.getProjectionMatrix = function (force) {
  14484. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14485. return this._projectionMatrix;
  14486. }
  14487. this._refreshFrustumPlanes = true;
  14488. var engine = this.getEngine();
  14489. var scene = this.getScene();
  14490. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14491. if (this.minZ <= 0) {
  14492. this.minZ = 0.1;
  14493. }
  14494. if (scene.useRightHandedSystem) {
  14495. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14496. }
  14497. else {
  14498. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14499. }
  14500. return this._projectionMatrix;
  14501. }
  14502. var halfWidth = engine.getRenderWidth() / 2.0;
  14503. var halfHeight = engine.getRenderHeight() / 2.0;
  14504. if (scene.useRightHandedSystem) {
  14505. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14506. }
  14507. else {
  14508. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14509. }
  14510. return this._projectionMatrix;
  14511. };
  14512. Camera.prototype.getTranformationMatrix = function () {
  14513. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14514. return this._transformMatrix;
  14515. };
  14516. Camera.prototype.updateFrustumPlanes = function () {
  14517. if (!this._refreshFrustumPlanes) {
  14518. return;
  14519. }
  14520. this.getTranformationMatrix();
  14521. if (!this._frustumPlanes) {
  14522. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14523. }
  14524. else {
  14525. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14526. }
  14527. this._refreshFrustumPlanes = false;
  14528. };
  14529. Camera.prototype.isInFrustum = function (target) {
  14530. this.updateFrustumPlanes();
  14531. return target.isInFrustum(this._frustumPlanes);
  14532. };
  14533. Camera.prototype.isCompletelyInFrustum = function (target) {
  14534. this.updateFrustumPlanes();
  14535. return target.isCompletelyInFrustum(this._frustumPlanes);
  14536. };
  14537. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14538. if (length === void 0) { length = 100; }
  14539. if (!transform) {
  14540. transform = this.getWorldMatrix();
  14541. }
  14542. if (!origin) {
  14543. origin = this.position;
  14544. }
  14545. var forward = new BABYLON.Vector3(0, 0, 1);
  14546. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14547. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14548. return new BABYLON.Ray(origin, direction, length);
  14549. };
  14550. Camera.prototype.dispose = function () {
  14551. // Animations
  14552. this.getScene().stopAnimation(this);
  14553. // Remove from scene
  14554. this.getScene().removeCamera(this);
  14555. while (this._rigCameras.length > 0) {
  14556. this._rigCameras.pop().dispose();
  14557. }
  14558. // Postprocesses
  14559. var i = this._postProcesses.length;
  14560. while (--i >= 0) {
  14561. this._postProcesses[i].dispose(this);
  14562. }
  14563. _super.prototype.dispose.call(this);
  14564. };
  14565. Object.defineProperty(Camera.prototype, "leftCamera", {
  14566. // ---- Camera rigs section ----
  14567. get: function () {
  14568. if (this._rigCameras.length < 1) {
  14569. return undefined;
  14570. }
  14571. return this._rigCameras[0];
  14572. },
  14573. enumerable: true,
  14574. configurable: true
  14575. });
  14576. Object.defineProperty(Camera.prototype, "rightCamera", {
  14577. get: function () {
  14578. if (this._rigCameras.length < 2) {
  14579. return undefined;
  14580. }
  14581. return this._rigCameras[1];
  14582. },
  14583. enumerable: true,
  14584. configurable: true
  14585. });
  14586. Camera.prototype.getLeftTarget = function () {
  14587. if (this._rigCameras.length < 1) {
  14588. return undefined;
  14589. }
  14590. return this._rigCameras[0].getTarget();
  14591. };
  14592. Camera.prototype.getRightTarget = function () {
  14593. if (this._rigCameras.length < 2) {
  14594. return undefined;
  14595. }
  14596. return this._rigCameras[1].getTarget();
  14597. };
  14598. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14599. while (this._rigCameras.length > 0) {
  14600. this._rigCameras.pop().dispose();
  14601. }
  14602. this.cameraRigMode = mode;
  14603. this._cameraRigParams = {};
  14604. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14605. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14606. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14607. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14608. // create the rig cameras, unless none
  14609. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14610. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14611. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14612. }
  14613. switch (this.cameraRigMode) {
  14614. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14615. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14616. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14617. break;
  14618. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14619. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14620. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14621. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14622. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14623. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14624. break;
  14625. case Camera.RIG_MODE_VR:
  14626. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14627. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14628. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14629. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14630. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14631. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14632. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14633. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14634. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14635. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14636. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14637. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14638. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14639. if (metrics.compensateDistortion) {
  14640. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14641. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14642. }
  14643. break;
  14644. case Camera.RIG_MODE_WEBVR:
  14645. if (rigParams.vrDisplay) {
  14646. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14647. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14648. //Left eye
  14649. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14650. this._rigCameras[0].setCameraRigParameter("left", true);
  14651. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14652. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14653. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14654. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14655. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14656. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14657. this._rigCameras[0].parent = this;
  14658. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14659. //Right eye
  14660. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14661. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14662. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14663. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14664. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14665. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14666. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14667. this._rigCameras[1].parent = this;
  14668. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14669. }
  14670. break;
  14671. }
  14672. this._cascadePostProcessesToRigCams();
  14673. this.
  14674. update();
  14675. };
  14676. Camera.prototype._getVRProjectionMatrix = function () {
  14677. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14678. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14679. return this._projectionMatrix;
  14680. };
  14681. Camera.prototype._updateCameraRotationMatrix = function () {
  14682. //Here for WebVR
  14683. };
  14684. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14685. //Here for WebVR
  14686. };
  14687. /**
  14688. * This function MUST be overwritten by the different WebVR cameras available.
  14689. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14690. */
  14691. Camera.prototype._getWebVRProjectionMatrix = function () {
  14692. return BABYLON.Matrix.Identity();
  14693. };
  14694. /**
  14695. * This function MUST be overwritten by the different WebVR cameras available.
  14696. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14697. */
  14698. Camera.prototype._getWebVRViewMatrix = function () {
  14699. return BABYLON.Matrix.Identity();
  14700. };
  14701. Camera.prototype.setCameraRigParameter = function (name, value) {
  14702. if (!this._cameraRigParams) {
  14703. this._cameraRigParams = {};
  14704. }
  14705. this._cameraRigParams[name] = value;
  14706. //provisionnally:
  14707. if (name === "interaxialDistance") {
  14708. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14709. }
  14710. };
  14711. /**
  14712. * needs to be overridden by children so sub has required properties to be copied
  14713. */
  14714. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14715. return null;
  14716. };
  14717. /**
  14718. * May need to be overridden by children
  14719. */
  14720. Camera.prototype._updateRigCameras = function () {
  14721. for (var i = 0; i < this._rigCameras.length; i++) {
  14722. this._rigCameras[i].minZ = this.minZ;
  14723. this._rigCameras[i].maxZ = this.maxZ;
  14724. this._rigCameras[i].fov = this.fov;
  14725. }
  14726. // only update viewport when ANAGLYPH
  14727. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14728. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14729. }
  14730. };
  14731. Camera.prototype._setupInputs = function () {
  14732. };
  14733. Camera.prototype.serialize = function () {
  14734. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14735. // Type
  14736. serializationObject.type = this.getClassName();
  14737. // Parent
  14738. if (this.parent) {
  14739. serializationObject.parentId = this.parent.id;
  14740. }
  14741. if (this.inputs) {
  14742. this.inputs.serialize(serializationObject);
  14743. }
  14744. // Animations
  14745. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14746. serializationObject.ranges = this.serializeAnimationRanges();
  14747. return serializationObject;
  14748. };
  14749. Camera.prototype.clone = function (name) {
  14750. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14751. };
  14752. Camera.prototype.getDirection = function (localAxis) {
  14753. var result = BABYLON.Vector3.Zero();
  14754. this.getDirectionToRef(localAxis, result);
  14755. return result;
  14756. };
  14757. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14758. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14759. };
  14760. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14761. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14762. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14763. switch (type) {
  14764. case "ArcRotateCamera":
  14765. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14766. case "DeviceOrientationCamera":
  14767. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14768. case "FollowCamera":
  14769. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14770. case "ArcFollowCamera":
  14771. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14772. case "GamepadCamera":
  14773. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14774. case "TouchCamera":
  14775. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14776. case "VirtualJoysticksCamera":
  14777. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14778. case "WebVRFreeCamera":
  14779. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14780. case "WebVRGamepadCamera":
  14781. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14782. case "VRDeviceOrientationFreeCamera":
  14783. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14784. case "VRDeviceOrientationGamepadCamera":
  14785. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14786. case "AnaglyphArcRotateCamera":
  14787. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14788. case "AnaglyphFreeCamera":
  14789. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14790. case "AnaglyphGamepadCamera":
  14791. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14792. case "AnaglyphUniversalCamera":
  14793. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14794. case "StereoscopicArcRotateCamera":
  14795. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14796. case "StereoscopicFreeCamera":
  14797. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14798. case "StereoscopicGamepadCamera":
  14799. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14800. case "StereoscopicUniversalCamera":
  14801. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14802. case "FreeCamera":
  14803. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14804. default:
  14805. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14806. }
  14807. };
  14808. Camera.Parse = function (parsedCamera, scene) {
  14809. var type = parsedCamera.type;
  14810. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14811. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14812. // Parent
  14813. if (parsedCamera.parentId) {
  14814. camera._waitingParentId = parsedCamera.parentId;
  14815. }
  14816. //If camera has an input manager, let it parse inputs settings
  14817. if (camera.inputs) {
  14818. camera.inputs.parse(parsedCamera);
  14819. camera._setupInputs();
  14820. }
  14821. if (camera.setPosition) {
  14822. camera.position.copyFromFloats(0, 0, 0);
  14823. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  14824. }
  14825. // Target
  14826. if (parsedCamera.target) {
  14827. if (camera.setTarget) {
  14828. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14829. }
  14830. }
  14831. // Apply 3d rig, when found
  14832. if (parsedCamera.cameraRigMode) {
  14833. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14834. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14835. }
  14836. // Animations
  14837. if (parsedCamera.animations) {
  14838. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14839. var parsedAnimation = parsedCamera.animations[animationIndex];
  14840. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14841. }
  14842. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14843. }
  14844. if (parsedCamera.autoAnimate) {
  14845. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14846. }
  14847. return camera;
  14848. };
  14849. return Camera;
  14850. }(BABYLON.Node));
  14851. // Statics
  14852. Camera._PERSPECTIVE_CAMERA = 0;
  14853. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14854. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14855. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14856. Camera._RIG_MODE_NONE = 0;
  14857. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14858. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14859. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14860. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14861. Camera._RIG_MODE_VR = 20;
  14862. Camera._RIG_MODE_WEBVR = 21;
  14863. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14864. __decorate([
  14865. BABYLON.serializeAsVector3()
  14866. ], Camera.prototype, "position", void 0);
  14867. __decorate([
  14868. BABYLON.serializeAsVector3()
  14869. ], Camera.prototype, "upVector", void 0);
  14870. __decorate([
  14871. BABYLON.serialize()
  14872. ], Camera.prototype, "orthoLeft", void 0);
  14873. __decorate([
  14874. BABYLON.serialize()
  14875. ], Camera.prototype, "orthoRight", void 0);
  14876. __decorate([
  14877. BABYLON.serialize()
  14878. ], Camera.prototype, "orthoBottom", void 0);
  14879. __decorate([
  14880. BABYLON.serialize()
  14881. ], Camera.prototype, "orthoTop", void 0);
  14882. __decorate([
  14883. BABYLON.serialize()
  14884. ], Camera.prototype, "fov", void 0);
  14885. __decorate([
  14886. BABYLON.serialize()
  14887. ], Camera.prototype, "minZ", void 0);
  14888. __decorate([
  14889. BABYLON.serialize()
  14890. ], Camera.prototype, "maxZ", void 0);
  14891. __decorate([
  14892. BABYLON.serialize()
  14893. ], Camera.prototype, "inertia", void 0);
  14894. __decorate([
  14895. BABYLON.serialize()
  14896. ], Camera.prototype, "mode", void 0);
  14897. __decorate([
  14898. BABYLON.serialize()
  14899. ], Camera.prototype, "layerMask", void 0);
  14900. __decorate([
  14901. BABYLON.serialize()
  14902. ], Camera.prototype, "fovMode", void 0);
  14903. __decorate([
  14904. BABYLON.serialize()
  14905. ], Camera.prototype, "cameraRigMode", void 0);
  14906. __decorate([
  14907. BABYLON.serialize()
  14908. ], Camera.prototype, "interaxialDistance", void 0);
  14909. __decorate([
  14910. BABYLON.serialize()
  14911. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14912. BABYLON.Camera = Camera;
  14913. })(BABYLON || (BABYLON = {}));
  14914. //# sourceMappingURL=babylon.camera.js.map
  14915. var BABYLON;
  14916. (function (BABYLON) {
  14917. var RenderingManager = (function () {
  14918. function RenderingManager(scene) {
  14919. this._renderingGroups = new Array();
  14920. this._autoClearDepthStencil = {};
  14921. this._customOpaqueSortCompareFn = {};
  14922. this._customAlphaTestSortCompareFn = {};
  14923. this._customTransparentSortCompareFn = {};
  14924. this._renderinGroupInfo = null;
  14925. this._scene = scene;
  14926. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14927. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14928. }
  14929. }
  14930. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14931. if (depth === void 0) { depth = true; }
  14932. if (stencil === void 0) { stencil = true; }
  14933. if (this._depthStencilBufferAlreadyCleaned) {
  14934. return;
  14935. }
  14936. this._scene.getEngine().clear(null, false, depth, stencil);
  14937. this._depthStencilBufferAlreadyCleaned = true;
  14938. };
  14939. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14940. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14941. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14942. var info = null;
  14943. if (observable) {
  14944. if (!this._renderinGroupInfo) {
  14945. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14946. }
  14947. info = this._renderinGroupInfo;
  14948. info.scene = this._scene;
  14949. info.camera = this._scene.activeCamera;
  14950. }
  14951. // Dispatch sprites
  14952. if (renderSprites) {
  14953. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14954. var manager = this._scene.spriteManagers[index];
  14955. this.dispatchSprites(manager);
  14956. }
  14957. }
  14958. // Render
  14959. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14960. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14961. var renderingGroup = this._renderingGroups[index];
  14962. if (!renderingGroup && !observable)
  14963. continue;
  14964. this._currentIndex = index;
  14965. var renderingGroupMask = 0;
  14966. // Fire PRECLEAR stage
  14967. if (observable) {
  14968. renderingGroupMask = Math.pow(2, index);
  14969. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14970. info.renderingGroupId = index;
  14971. observable.notifyObservers(info, renderingGroupMask);
  14972. }
  14973. // Clear depth/stencil if needed
  14974. if (RenderingManager.AUTOCLEAR) {
  14975. var autoClear = this._autoClearDepthStencil[index];
  14976. if (autoClear && autoClear.autoClear) {
  14977. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14978. }
  14979. }
  14980. if (observable) {
  14981. // Fire PREOPAQUE stage
  14982. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14983. observable.notifyObservers(info, renderingGroupMask);
  14984. // Fire PRETRANSPARENT stage
  14985. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14986. observable.notifyObservers(info, renderingGroupMask);
  14987. }
  14988. if (renderingGroup)
  14989. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14990. // Fire POSTTRANSPARENT stage
  14991. if (observable) {
  14992. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14993. observable.notifyObservers(info, renderingGroupMask);
  14994. }
  14995. }
  14996. };
  14997. RenderingManager.prototype.reset = function () {
  14998. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14999. var renderingGroup = this._renderingGroups[index];
  15000. if (renderingGroup) {
  15001. renderingGroup.prepare();
  15002. }
  15003. }
  15004. };
  15005. RenderingManager.prototype.dispose = function () {
  15006. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15007. var renderingGroup = this._renderingGroups[index];
  15008. if (renderingGroup) {
  15009. renderingGroup.dispose();
  15010. }
  15011. }
  15012. this._renderingGroups.length = 0;
  15013. };
  15014. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15015. if (!this._renderingGroups[renderingGroupId]) {
  15016. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15017. }
  15018. };
  15019. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15020. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15021. this._prepareRenderingGroup(renderingGroupId);
  15022. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15023. };
  15024. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15025. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15026. this._prepareRenderingGroup(renderingGroupId);
  15027. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15028. };
  15029. RenderingManager.prototype.dispatch = function (subMesh) {
  15030. var mesh = subMesh.getMesh();
  15031. var renderingGroupId = mesh.renderingGroupId || 0;
  15032. this._prepareRenderingGroup(renderingGroupId);
  15033. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15034. };
  15035. /**
  15036. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15037. * This allowed control for front to back rendering or reversly depending of the special needs.
  15038. *
  15039. * @param renderingGroupId The rendering group id corresponding to its index
  15040. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15041. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15042. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15043. */
  15044. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15045. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15046. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15047. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15048. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15049. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15050. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15051. if (this._renderingGroups[renderingGroupId]) {
  15052. var group = this._renderingGroups[renderingGroupId];
  15053. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15054. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15055. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15056. }
  15057. };
  15058. /**
  15059. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15060. *
  15061. * @param renderingGroupId The rendering group id corresponding to its index
  15062. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15063. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15064. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15065. */
  15066. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15067. if (depth === void 0) { depth = true; }
  15068. if (stencil === void 0) { stencil = true; }
  15069. this._autoClearDepthStencil[renderingGroupId] = {
  15070. autoClear: autoClearDepthStencil,
  15071. depth: depth,
  15072. stencil: stencil
  15073. };
  15074. };
  15075. return RenderingManager;
  15076. }());
  15077. /**
  15078. * The max id used for rendering groups (not included)
  15079. */
  15080. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15081. /**
  15082. * The min id used for rendering groups (included)
  15083. */
  15084. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15085. /**
  15086. * Used to globally prevent autoclearing scenes.
  15087. */
  15088. RenderingManager.AUTOCLEAR = true;
  15089. BABYLON.RenderingManager = RenderingManager;
  15090. })(BABYLON || (BABYLON = {}));
  15091. //# sourceMappingURL=babylon.renderingManager.js.map
  15092. var BABYLON;
  15093. (function (BABYLON) {
  15094. var RenderingGroup = (function () {
  15095. /**
  15096. * Creates a new rendering group.
  15097. * @param index The rendering group index
  15098. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15099. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15100. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15101. */
  15102. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15103. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15104. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15105. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15106. this.index = index;
  15107. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15108. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15109. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15110. this._particleSystems = new BABYLON.SmartArray(256);
  15111. this._spriteManagers = new BABYLON.SmartArray(256);
  15112. this._edgesRenderers = new BABYLON.SmartArray(16);
  15113. this._scene = scene;
  15114. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15115. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15116. this.transparentSortCompareFn = transparentSortCompareFn;
  15117. }
  15118. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15119. /**
  15120. * Set the opaque sort comparison function.
  15121. * If null the sub meshes will be render in the order they were created
  15122. */
  15123. set: function (value) {
  15124. this._opaqueSortCompareFn = value;
  15125. if (value) {
  15126. this._renderOpaque = this.renderOpaqueSorted;
  15127. }
  15128. else {
  15129. this._renderOpaque = RenderingGroup.renderUnsorted;
  15130. }
  15131. },
  15132. enumerable: true,
  15133. configurable: true
  15134. });
  15135. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15136. /**
  15137. * Set the alpha test sort comparison function.
  15138. * If null the sub meshes will be render in the order they were created
  15139. */
  15140. set: function (value) {
  15141. this._alphaTestSortCompareFn = value;
  15142. if (value) {
  15143. this._renderAlphaTest = this.renderAlphaTestSorted;
  15144. }
  15145. else {
  15146. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15147. }
  15148. },
  15149. enumerable: true,
  15150. configurable: true
  15151. });
  15152. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15153. /**
  15154. * Set the transparent sort comparison function.
  15155. * If null the sub meshes will be render in the order they were created
  15156. */
  15157. set: function (value) {
  15158. if (value) {
  15159. this._transparentSortCompareFn = value;
  15160. }
  15161. else {
  15162. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15163. }
  15164. this._renderTransparent = this.renderTransparentSorted;
  15165. },
  15166. enumerable: true,
  15167. configurable: true
  15168. });
  15169. /**
  15170. * Render all the sub meshes contained in the group.
  15171. * @param customRenderFunction Used to override the default render behaviour of the group.
  15172. * @returns true if rendered some submeshes.
  15173. */
  15174. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15175. if (customRenderFunction) {
  15176. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15177. return;
  15178. }
  15179. var engine = this._scene.getEngine();
  15180. // Opaque
  15181. if (this._opaqueSubMeshes.length !== 0) {
  15182. this._renderOpaque(this._opaqueSubMeshes);
  15183. }
  15184. // Alpha test
  15185. if (this._alphaTestSubMeshes.length !== 0) {
  15186. engine.setAlphaTesting(true);
  15187. this._renderAlphaTest(this._alphaTestSubMeshes);
  15188. engine.setAlphaTesting(false);
  15189. }
  15190. var stencilState = engine.getStencilBuffer();
  15191. engine.setStencilBuffer(false);
  15192. // Sprites
  15193. if (renderSprites) {
  15194. this._renderSprites();
  15195. }
  15196. // Particles
  15197. if (renderParticles) {
  15198. this._renderParticles(activeMeshes);
  15199. }
  15200. if (this.onBeforeTransparentRendering) {
  15201. this.onBeforeTransparentRendering();
  15202. }
  15203. // Transparent
  15204. if (this._transparentSubMeshes.length !== 0) {
  15205. this._renderTransparent(this._transparentSubMeshes);
  15206. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15207. }
  15208. engine.setStencilBuffer(stencilState);
  15209. // Edges
  15210. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15211. this._edgesRenderers.data[edgesRendererIndex].render();
  15212. }
  15213. };
  15214. /**
  15215. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15216. * @param subMeshes The submeshes to render
  15217. */
  15218. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15219. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15220. };
  15221. /**
  15222. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15223. * @param subMeshes The submeshes to render
  15224. */
  15225. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15226. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15227. };
  15228. /**
  15229. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15230. * @param subMeshes The submeshes to render
  15231. */
  15232. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15233. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15234. };
  15235. /**
  15236. * Renders the submeshes in a specified order.
  15237. * @param subMeshes The submeshes to sort before render
  15238. * @param sortCompareFn The comparison function use to sort
  15239. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15240. * @param transparent Specifies to activate blending if true
  15241. */
  15242. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15243. var subIndex = 0;
  15244. var subMesh;
  15245. for (; subIndex < subMeshes.length; subIndex++) {
  15246. subMesh = subMeshes.data[subIndex];
  15247. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15248. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15249. }
  15250. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15251. sortedArray.sort(sortCompareFn);
  15252. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15253. subMesh = sortedArray[subIndex];
  15254. subMesh.render(transparent);
  15255. }
  15256. };
  15257. /**
  15258. * Renders the submeshes in the order they were dispatched (no sort applied).
  15259. * @param subMeshes The submeshes to render
  15260. */
  15261. RenderingGroup.renderUnsorted = function (subMeshes) {
  15262. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15263. var submesh = subMeshes.data[subIndex];
  15264. submesh.render(false);
  15265. }
  15266. };
  15267. /**
  15268. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15269. * are rendered back to front if in the same alpha index.
  15270. *
  15271. * @param a The first submesh
  15272. * @param b The second submesh
  15273. * @returns The result of the comparison
  15274. */
  15275. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15276. // Alpha index first
  15277. if (a._alphaIndex > b._alphaIndex) {
  15278. return 1;
  15279. }
  15280. if (a._alphaIndex < b._alphaIndex) {
  15281. return -1;
  15282. }
  15283. // Then distance to camera
  15284. return RenderingGroup.backToFrontSortCompare(a, b);
  15285. };
  15286. /**
  15287. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15288. * are rendered back to front.
  15289. *
  15290. * @param a The first submesh
  15291. * @param b The second submesh
  15292. * @returns The result of the comparison
  15293. */
  15294. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15295. // Then distance to camera
  15296. if (a._distanceToCamera < b._distanceToCamera) {
  15297. return 1;
  15298. }
  15299. if (a._distanceToCamera > b._distanceToCamera) {
  15300. return -1;
  15301. }
  15302. return 0;
  15303. };
  15304. /**
  15305. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15306. * are rendered front to back (prevent overdraw).
  15307. *
  15308. * @param a The first submesh
  15309. * @param b The second submesh
  15310. * @returns The result of the comparison
  15311. */
  15312. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15313. // Then distance to camera
  15314. if (a._distanceToCamera < b._distanceToCamera) {
  15315. return -1;
  15316. }
  15317. if (a._distanceToCamera > b._distanceToCamera) {
  15318. return 1;
  15319. }
  15320. return 0;
  15321. };
  15322. /**
  15323. * Resets the different lists of submeshes to prepare a new frame.
  15324. */
  15325. RenderingGroup.prototype.prepare = function () {
  15326. this._opaqueSubMeshes.reset();
  15327. this._transparentSubMeshes.reset();
  15328. this._alphaTestSubMeshes.reset();
  15329. this._particleSystems.reset();
  15330. this._spriteManagers.reset();
  15331. this._edgesRenderers.reset();
  15332. };
  15333. RenderingGroup.prototype.dispose = function () {
  15334. this._opaqueSubMeshes.dispose();
  15335. this._transparentSubMeshes.dispose();
  15336. this._alphaTestSubMeshes.dispose();
  15337. this._particleSystems.dispose();
  15338. this._spriteManagers.dispose();
  15339. this._edgesRenderers.dispose();
  15340. };
  15341. /**
  15342. * Inserts the submesh in its correct queue depending on its material.
  15343. * @param subMesh The submesh to dispatch
  15344. */
  15345. RenderingGroup.prototype.dispatch = function (subMesh) {
  15346. var material = subMesh.getMaterial();
  15347. var mesh = subMesh.getMesh();
  15348. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15349. this._transparentSubMeshes.push(subMesh);
  15350. }
  15351. else if (material.needAlphaTesting()) {
  15352. this._alphaTestSubMeshes.push(subMesh);
  15353. }
  15354. else {
  15355. this._opaqueSubMeshes.push(subMesh); // Opaque
  15356. }
  15357. if (mesh._edgesRenderer) {
  15358. this._edgesRenderers.push(mesh._edgesRenderer);
  15359. }
  15360. };
  15361. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15362. this._spriteManagers.push(spriteManager);
  15363. };
  15364. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15365. this._particleSystems.push(particleSystem);
  15366. };
  15367. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15368. if (this._particleSystems.length === 0) {
  15369. return;
  15370. }
  15371. // Particles
  15372. var activeCamera = this._scene.activeCamera;
  15373. this._scene._particlesDuration.beginMonitoring();
  15374. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15375. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15376. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15377. continue;
  15378. }
  15379. var emitter = particleSystem.emitter;
  15380. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  15381. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15382. }
  15383. }
  15384. this._scene._particlesDuration.endMonitoring(false);
  15385. };
  15386. RenderingGroup.prototype._renderSprites = function () {
  15387. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15388. return;
  15389. }
  15390. // Sprites
  15391. var activeCamera = this._scene.activeCamera;
  15392. this._scene._spritesDuration.beginMonitoring();
  15393. for (var id = 0; id < this._spriteManagers.length; id++) {
  15394. var spriteManager = this._spriteManagers.data[id];
  15395. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15396. spriteManager.render();
  15397. }
  15398. }
  15399. this._scene._spritesDuration.endMonitoring(false);
  15400. };
  15401. return RenderingGroup;
  15402. }());
  15403. BABYLON.RenderingGroup = RenderingGroup;
  15404. })(BABYLON || (BABYLON = {}));
  15405. //# sourceMappingURL=babylon.renderingGroup.js.map
  15406. var BABYLON;
  15407. (function (BABYLON) {
  15408. var ClickInfo = (function () {
  15409. function ClickInfo() {
  15410. this._singleClick = false;
  15411. this._doubleClick = false;
  15412. this._hasSwiped = false;
  15413. this._ignore = false;
  15414. }
  15415. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15416. get: function () {
  15417. return this._singleClick;
  15418. },
  15419. set: function (b) {
  15420. this._singleClick = b;
  15421. },
  15422. enumerable: true,
  15423. configurable: true
  15424. });
  15425. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15426. get: function () {
  15427. return this._doubleClick;
  15428. },
  15429. set: function (b) {
  15430. this._doubleClick = b;
  15431. },
  15432. enumerable: true,
  15433. configurable: true
  15434. });
  15435. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15436. get: function () {
  15437. return this._hasSwiped;
  15438. },
  15439. set: function (b) {
  15440. this._hasSwiped = b;
  15441. },
  15442. enumerable: true,
  15443. configurable: true
  15444. });
  15445. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15446. get: function () {
  15447. return this._ignore;
  15448. },
  15449. set: function (b) {
  15450. this._ignore = b;
  15451. },
  15452. enumerable: true,
  15453. configurable: true
  15454. });
  15455. return ClickInfo;
  15456. }());
  15457. var PointerEventTypes = (function () {
  15458. function PointerEventTypes() {
  15459. }
  15460. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15461. get: function () {
  15462. return PointerEventTypes._POINTERDOWN;
  15463. },
  15464. enumerable: true,
  15465. configurable: true
  15466. });
  15467. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15468. get: function () {
  15469. return PointerEventTypes._POINTERUP;
  15470. },
  15471. enumerable: true,
  15472. configurable: true
  15473. });
  15474. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15475. get: function () {
  15476. return PointerEventTypes._POINTERMOVE;
  15477. },
  15478. enumerable: true,
  15479. configurable: true
  15480. });
  15481. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15482. get: function () {
  15483. return PointerEventTypes._POINTERWHEEL;
  15484. },
  15485. enumerable: true,
  15486. configurable: true
  15487. });
  15488. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15489. get: function () {
  15490. return PointerEventTypes._POINTERPICK;
  15491. },
  15492. enumerable: true,
  15493. configurable: true
  15494. });
  15495. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15496. get: function () {
  15497. return PointerEventTypes._POINTERTAP;
  15498. },
  15499. enumerable: true,
  15500. configurable: true
  15501. });
  15502. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15503. get: function () {
  15504. return PointerEventTypes._POINTERDOUBLETAP;
  15505. },
  15506. enumerable: true,
  15507. configurable: true
  15508. });
  15509. return PointerEventTypes;
  15510. }());
  15511. PointerEventTypes._POINTERDOWN = 0x01;
  15512. PointerEventTypes._POINTERUP = 0x02;
  15513. PointerEventTypes._POINTERMOVE = 0x04;
  15514. PointerEventTypes._POINTERWHEEL = 0x08;
  15515. PointerEventTypes._POINTERPICK = 0x10;
  15516. PointerEventTypes._POINTERTAP = 0x20;
  15517. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15518. BABYLON.PointerEventTypes = PointerEventTypes;
  15519. var PointerInfoBase = (function () {
  15520. function PointerInfoBase(type, event) {
  15521. this.type = type;
  15522. this.event = event;
  15523. }
  15524. return PointerInfoBase;
  15525. }());
  15526. BABYLON.PointerInfoBase = PointerInfoBase;
  15527. /**
  15528. * This class is used to store pointer related info for the onPrePointerObservable event.
  15529. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15530. */
  15531. var PointerInfoPre = (function (_super) {
  15532. __extends(PointerInfoPre, _super);
  15533. function PointerInfoPre(type, event, localX, localY) {
  15534. var _this = _super.call(this, type, event) || this;
  15535. _this.skipOnPointerObservable = false;
  15536. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15537. return _this;
  15538. }
  15539. return PointerInfoPre;
  15540. }(PointerInfoBase));
  15541. BABYLON.PointerInfoPre = PointerInfoPre;
  15542. /**
  15543. * This type contains all the data related to a pointer event in Babylon.js.
  15544. * 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.
  15545. */
  15546. var PointerInfo = (function (_super) {
  15547. __extends(PointerInfo, _super);
  15548. function PointerInfo(type, event, pickInfo) {
  15549. var _this = _super.call(this, type, event) || this;
  15550. _this.pickInfo = pickInfo;
  15551. return _this;
  15552. }
  15553. return PointerInfo;
  15554. }(PointerInfoBase));
  15555. BABYLON.PointerInfo = PointerInfo;
  15556. /**
  15557. * This class is used by the onRenderingGroupObservable
  15558. */
  15559. var RenderingGroupInfo = (function () {
  15560. function RenderingGroupInfo() {
  15561. }
  15562. return RenderingGroupInfo;
  15563. }());
  15564. /**
  15565. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15566. * This stage will be fired no matter what
  15567. */
  15568. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15569. /**
  15570. * Called before opaque object are rendered.
  15571. * This stage will be fired only if there's 3D Opaque content to render
  15572. */
  15573. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15574. /**
  15575. * Called after the opaque objects are rendered and before the transparent ones
  15576. * This stage will be fired only if there's 3D transparent content to render
  15577. */
  15578. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15579. /**
  15580. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15581. * This stage will be fired no matter what
  15582. */
  15583. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15584. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15585. /**
  15586. * Represents a scene to be rendered by the engine.
  15587. * @see http://doc.babylonjs.com/page.php?p=21911
  15588. */
  15589. var Scene = (function () {
  15590. /**
  15591. * @constructor
  15592. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15593. */
  15594. function Scene(engine) {
  15595. // Members
  15596. this.autoClear = true;
  15597. this.autoClearDepthAndStencil = true;
  15598. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15599. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15600. this.forceWireframe = false;
  15601. this._forcePointsCloud = false;
  15602. this.forceShowBoundingBoxes = false;
  15603. this.animationsEnabled = true;
  15604. this.constantlyUpdateMeshUnderPointer = false;
  15605. this.hoverCursor = "pointer";
  15606. // Metadata
  15607. this.metadata = null;
  15608. // Events
  15609. /**
  15610. * An event triggered when the scene is disposed.
  15611. * @type {BABYLON.Observable}
  15612. */
  15613. this.onDisposeObservable = new BABYLON.Observable();
  15614. /**
  15615. * An event triggered before rendering the scene
  15616. * @type {BABYLON.Observable}
  15617. */
  15618. this.onBeforeRenderObservable = new BABYLON.Observable();
  15619. /**
  15620. * An event triggered after rendering the scene
  15621. * @type {BABYLON.Observable}
  15622. */
  15623. this.onAfterRenderObservable = new BABYLON.Observable();
  15624. /**
  15625. * An event triggered when the scene is ready
  15626. * @type {BABYLON.Observable}
  15627. */
  15628. this.onReadyObservable = new BABYLON.Observable();
  15629. /**
  15630. * An event triggered before rendering a camera
  15631. * @type {BABYLON.Observable}
  15632. */
  15633. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15634. /**
  15635. * An event triggered after rendering a camera
  15636. * @type {BABYLON.Observable}
  15637. */
  15638. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15639. /**
  15640. * An event triggered when a camera is created
  15641. * @type {BABYLON.Observable}
  15642. */
  15643. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15644. /**
  15645. * An event triggered when a camera is removed
  15646. * @type {BABYLON.Observable}
  15647. */
  15648. this.onCameraRemovedObservable = new BABYLON.Observable();
  15649. /**
  15650. * An event triggered when a light is created
  15651. * @type {BABYLON.Observable}
  15652. */
  15653. this.onNewLightAddedObservable = new BABYLON.Observable();
  15654. /**
  15655. * An event triggered when a light is removed
  15656. * @type {BABYLON.Observable}
  15657. */
  15658. this.onLightRemovedObservable = new BABYLON.Observable();
  15659. /**
  15660. * An event triggered when a geometry is created
  15661. * @type {BABYLON.Observable}
  15662. */
  15663. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15664. /**
  15665. * An event triggered when a geometry is removed
  15666. * @type {BABYLON.Observable}
  15667. */
  15668. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15669. /**
  15670. * An event triggered when a mesh is created
  15671. * @type {BABYLON.Observable}
  15672. */
  15673. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15674. /**
  15675. * An event triggered when a mesh is removed
  15676. * @type {BABYLON.Observable}
  15677. */
  15678. this.onMeshRemovedObservable = new BABYLON.Observable();
  15679. /**
  15680. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15681. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15682. * 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)
  15683. */
  15684. this.onRenderingGroupObservable = new BABYLON.Observable();
  15685. // Animations
  15686. this.animations = [];
  15687. /**
  15688. * 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).
  15689. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15690. */
  15691. this.onPrePointerObservable = new BABYLON.Observable();
  15692. /**
  15693. * Observable event triggered each time an input event is received from the rendering canvas
  15694. */
  15695. this.onPointerObservable = new BABYLON.Observable();
  15696. this._meshPickProceed = false;
  15697. this._previousHasSwiped = false;
  15698. this._currentPickResult = null;
  15699. this._previousPickResult = null;
  15700. this._isButtonPressed = false;
  15701. this._doubleClickOccured = false;
  15702. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  15703. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15704. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15705. this._startingPointerTime = 0;
  15706. this._previousStartingPointerTime = 0;
  15707. // Coordinate system
  15708. /**
  15709. * use right-handed coordinate system on this scene.
  15710. * @type {boolean}
  15711. */
  15712. this._useRightHandedSystem = false;
  15713. // Fog
  15714. /**
  15715. * is fog enabled on this scene.
  15716. * @type {boolean}
  15717. */
  15718. this._fogEnabled = true;
  15719. this._fogMode = Scene.FOGMODE_NONE;
  15720. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15721. this.fogDensity = 0.1;
  15722. this.fogStart = 0;
  15723. this.fogEnd = 1000.0;
  15724. // Lights
  15725. /**
  15726. * is shadow enabled on this scene.
  15727. * @type {boolean}
  15728. */
  15729. this._shadowsEnabled = true;
  15730. /**
  15731. * is light enabled on this scene.
  15732. * @type {boolean}
  15733. */
  15734. this._lightsEnabled = true;
  15735. /**
  15736. * All of the lights added to this scene.
  15737. * @see BABYLON.Light
  15738. * @type {BABYLON.Light[]}
  15739. */
  15740. this.lights = new Array();
  15741. // Cameras
  15742. /**
  15743. * All of the cameras added to this scene.
  15744. * @see BABYLON.Camera
  15745. * @type {BABYLON.Camera[]}
  15746. */
  15747. this.cameras = new Array();
  15748. this.activeCameras = new Array();
  15749. // Meshes
  15750. /**
  15751. * All of the (abstract) meshes added to this scene.
  15752. * @see BABYLON.AbstractMesh
  15753. * @type {BABYLON.AbstractMesh[]}
  15754. */
  15755. this.meshes = new Array();
  15756. // Geometries
  15757. this._geometries = new Array();
  15758. this.materials = new Array();
  15759. this.multiMaterials = new Array();
  15760. // Textures
  15761. this._texturesEnabled = true;
  15762. this.textures = new Array();
  15763. // Particles
  15764. this.particlesEnabled = true;
  15765. this.particleSystems = new Array();
  15766. // Sprites
  15767. this.spritesEnabled = true;
  15768. this.spriteManagers = new Array();
  15769. // Layers
  15770. this.layers = new Array();
  15771. this.highlightLayers = new Array();
  15772. // Skeletons
  15773. this._skeletonsEnabled = true;
  15774. this.skeletons = new Array();
  15775. // Morph targets
  15776. this.morphTargetManagers = new Array();
  15777. // Lens flares
  15778. this.lensFlaresEnabled = true;
  15779. this.lensFlareSystems = new Array();
  15780. // Collisions
  15781. this.collisionsEnabled = true;
  15782. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15783. // Postprocesses
  15784. this.postProcessesEnabled = true;
  15785. // Customs render targets
  15786. this.renderTargetsEnabled = true;
  15787. this.dumpNextRenderTargets = false;
  15788. this.customRenderTargets = new Array();
  15789. // Imported meshes
  15790. this.importedMeshesFiles = new Array();
  15791. // Probes
  15792. this.probesEnabled = true;
  15793. this.reflectionProbes = new Array();
  15794. this._actionManagers = new Array();
  15795. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15796. // Procedural textures
  15797. this.proceduralTexturesEnabled = true;
  15798. this._proceduralTextures = new Array();
  15799. this.soundTracks = new Array();
  15800. this._audioEnabled = true;
  15801. this._headphone = false;
  15802. // Performance counters
  15803. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15804. this._totalLightsCounter = new BABYLON.PerfCounter();
  15805. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15806. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15807. this._totalVertices = new BABYLON.PerfCounter();
  15808. this._activeIndices = new BABYLON.PerfCounter();
  15809. this._activeParticles = new BABYLON.PerfCounter();
  15810. this._lastFrameDuration = new BABYLON.PerfCounter();
  15811. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15812. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15813. this._particlesDuration = new BABYLON.PerfCounter();
  15814. this._renderDuration = new BABYLON.PerfCounter();
  15815. this._spritesDuration = new BABYLON.PerfCounter();
  15816. this._activeBones = new BABYLON.PerfCounter();
  15817. this._animationTime = 0;
  15818. this.animationTimeScale = 1;
  15819. this._renderId = 0;
  15820. this._executeWhenReadyTimeoutId = -1;
  15821. this._intermediateRendering = false;
  15822. this._viewUpdateFlag = -1;
  15823. this._projectionUpdateFlag = -1;
  15824. this._toBeDisposed = new BABYLON.SmartArray(256);
  15825. this._pendingData = []; //ANY
  15826. this._activeMeshes = new BABYLON.SmartArray(256);
  15827. this._processedMaterials = new BABYLON.SmartArray(256);
  15828. this._renderTargets = new BABYLON.SmartArray(256);
  15829. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15830. this._activeSkeletons = new BABYLON.SmartArray(32);
  15831. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15832. this._activeAnimatables = new Array();
  15833. this._transformMatrix = BABYLON.Matrix.Zero();
  15834. this.requireLightSorting = false;
  15835. this._uniqueIdCounter = 0;
  15836. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15837. this._engine.scenes.push(this);
  15838. this._uid = null;
  15839. this._renderingManager = new BABYLON.RenderingManager(this);
  15840. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15841. if (BABYLON.OutlineRenderer) {
  15842. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15843. }
  15844. this.attachControl();
  15845. if (BABYLON.SoundTrack) {
  15846. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15847. }
  15848. //simplification queue
  15849. if (BABYLON.SimplificationQueue) {
  15850. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15851. }
  15852. //collision coordinator initialization. For now legacy per default.
  15853. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15854. // Uniform Buffer
  15855. this._createUbo();
  15856. // Default Image processing definition.
  15857. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  15858. }
  15859. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15860. get: function () {
  15861. return Scene._FOGMODE_NONE;
  15862. },
  15863. enumerable: true,
  15864. configurable: true
  15865. });
  15866. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15867. get: function () {
  15868. return Scene._FOGMODE_EXP;
  15869. },
  15870. enumerable: true,
  15871. configurable: true
  15872. });
  15873. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15874. get: function () {
  15875. return Scene._FOGMODE_EXP2;
  15876. },
  15877. enumerable: true,
  15878. configurable: true
  15879. });
  15880. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15881. get: function () {
  15882. return Scene._FOGMODE_LINEAR;
  15883. },
  15884. enumerable: true,
  15885. configurable: true
  15886. });
  15887. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15888. /**
  15889. * Texture used in all pbr material as the reflection texture.
  15890. * As in the majority of the scene they are the same (exception for multi room and so on),
  15891. * this is easier to reference from here than from all the materials.
  15892. */
  15893. get: function () {
  15894. return this._environmentTexture;
  15895. },
  15896. /**
  15897. * Texture used in all pbr material as the reflection texture.
  15898. * As in the majority of the scene they are the same (exception for multi room and so on),
  15899. * this is easier to set here than in all the materials.
  15900. */
  15901. set: function (value) {
  15902. this._environmentTexture = value;
  15903. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  15909. /**
  15910. * Default image processing configuration used either in the rendering
  15911. * Forward main pass or through the imageProcessingPostProcess if present.
  15912. * As in the majority of the scene they are the same (exception for multi camera),
  15913. * this is easier to reference from here than from all the materials and post process.
  15914. *
  15915. * No setter as we it is a shared configuration, you can set the values instead.
  15916. */
  15917. get: function () {
  15918. return this._imageProcessingConfiguration;
  15919. },
  15920. enumerable: true,
  15921. configurable: true
  15922. });
  15923. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15924. get: function () {
  15925. return this._forcePointsCloud;
  15926. },
  15927. set: function (value) {
  15928. if (this._forcePointsCloud === value) {
  15929. return;
  15930. }
  15931. this._forcePointsCloud = value;
  15932. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15933. },
  15934. enumerable: true,
  15935. configurable: true
  15936. });
  15937. Object.defineProperty(Scene.prototype, "onDispose", {
  15938. set: function (callback) {
  15939. if (this._onDisposeObserver) {
  15940. this.onDisposeObservable.remove(this._onDisposeObserver);
  15941. }
  15942. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15943. },
  15944. enumerable: true,
  15945. configurable: true
  15946. });
  15947. Object.defineProperty(Scene.prototype, "beforeRender", {
  15948. set: function (callback) {
  15949. if (this._onBeforeRenderObserver) {
  15950. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15951. }
  15952. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15953. },
  15954. enumerable: true,
  15955. configurable: true
  15956. });
  15957. Object.defineProperty(Scene.prototype, "afterRender", {
  15958. set: function (callback) {
  15959. if (this._onAfterRenderObserver) {
  15960. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15961. }
  15962. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15963. },
  15964. enumerable: true,
  15965. configurable: true
  15966. });
  15967. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15968. set: function (callback) {
  15969. if (this._onBeforeCameraRenderObserver) {
  15970. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15971. }
  15972. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15973. },
  15974. enumerable: true,
  15975. configurable: true
  15976. });
  15977. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15978. set: function (callback) {
  15979. if (this._onAfterCameraRenderObserver) {
  15980. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15981. }
  15982. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15983. },
  15984. enumerable: true,
  15985. configurable: true
  15986. });
  15987. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15988. get: function () {
  15989. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15990. },
  15991. enumerable: true,
  15992. configurable: true
  15993. });
  15994. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15995. get: function () {
  15996. return this._useRightHandedSystem;
  15997. },
  15998. set: function (value) {
  15999. if (this._useRightHandedSystem === value) {
  16000. return;
  16001. }
  16002. this._useRightHandedSystem = value;
  16003. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16004. },
  16005. enumerable: true,
  16006. configurable: true
  16007. });
  16008. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16009. get: function () {
  16010. return this._fogEnabled;
  16011. },
  16012. set: function (value) {
  16013. if (this._fogEnabled === value) {
  16014. return;
  16015. }
  16016. this._fogEnabled = value;
  16017. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16018. },
  16019. enumerable: true,
  16020. configurable: true
  16021. });
  16022. Object.defineProperty(Scene.prototype, "fogMode", {
  16023. get: function () {
  16024. return this._fogMode;
  16025. },
  16026. set: function (value) {
  16027. if (this._fogMode === value) {
  16028. return;
  16029. }
  16030. this._fogMode = value;
  16031. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16032. },
  16033. enumerable: true,
  16034. configurable: true
  16035. });
  16036. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16037. get: function () {
  16038. return this._shadowsEnabled;
  16039. },
  16040. set: function (value) {
  16041. if (this._shadowsEnabled === value) {
  16042. return;
  16043. }
  16044. this._shadowsEnabled = value;
  16045. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16046. },
  16047. enumerable: true,
  16048. configurable: true
  16049. });
  16050. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16051. get: function () {
  16052. return this._lightsEnabled;
  16053. },
  16054. set: function (value) {
  16055. if (this._lightsEnabled === value) {
  16056. return;
  16057. }
  16058. this._lightsEnabled = value;
  16059. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16060. },
  16061. enumerable: true,
  16062. configurable: true
  16063. });
  16064. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16065. get: function () {
  16066. if (!this._defaultMaterial) {
  16067. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16068. }
  16069. return this._defaultMaterial;
  16070. },
  16071. set: function (value) {
  16072. this._defaultMaterial = value;
  16073. },
  16074. enumerable: true,
  16075. configurable: true
  16076. });
  16077. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16078. get: function () {
  16079. return this._texturesEnabled;
  16080. },
  16081. set: function (value) {
  16082. if (this._texturesEnabled === value) {
  16083. return;
  16084. }
  16085. this._texturesEnabled = value;
  16086. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16087. },
  16088. enumerable: true,
  16089. configurable: true
  16090. });
  16091. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16092. get: function () {
  16093. return this._skeletonsEnabled;
  16094. },
  16095. set: function (value) {
  16096. if (this._skeletonsEnabled === value) {
  16097. return;
  16098. }
  16099. this._skeletonsEnabled = value;
  16100. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16101. },
  16102. enumerable: true,
  16103. configurable: true
  16104. });
  16105. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16106. get: function () {
  16107. if (!this._postProcessRenderPipelineManager) {
  16108. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16109. }
  16110. return this._postProcessRenderPipelineManager;
  16111. },
  16112. enumerable: true,
  16113. configurable: true
  16114. });
  16115. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16116. get: function () {
  16117. return this._frustumPlanes;
  16118. },
  16119. enumerable: true,
  16120. configurable: true
  16121. });
  16122. Object.defineProperty(Scene.prototype, "debugLayer", {
  16123. // Properties
  16124. get: function () {
  16125. if (!this._debugLayer) {
  16126. this._debugLayer = new BABYLON.DebugLayer(this);
  16127. }
  16128. return this._debugLayer;
  16129. },
  16130. enumerable: true,
  16131. configurable: true
  16132. });
  16133. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16134. get: function () {
  16135. return this._workerCollisions;
  16136. },
  16137. set: function (enabled) {
  16138. if (!BABYLON.CollisionCoordinatorLegacy) {
  16139. return;
  16140. }
  16141. enabled = (enabled && !!Worker);
  16142. this._workerCollisions = enabled;
  16143. if (this.collisionCoordinator) {
  16144. this.collisionCoordinator.destroy();
  16145. }
  16146. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16147. this.collisionCoordinator.init(this);
  16148. },
  16149. enumerable: true,
  16150. configurable: true
  16151. });
  16152. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16153. get: function () {
  16154. return this._selectionOctree;
  16155. },
  16156. enumerable: true,
  16157. configurable: true
  16158. });
  16159. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16160. /**
  16161. * The mesh that is currently under the pointer.
  16162. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16163. */
  16164. get: function () {
  16165. return this._pointerOverMesh;
  16166. },
  16167. enumerable: true,
  16168. configurable: true
  16169. });
  16170. Object.defineProperty(Scene.prototype, "pointerX", {
  16171. /**
  16172. * Current on-screen X position of the pointer
  16173. * @return {number} X position of the pointer
  16174. */
  16175. get: function () {
  16176. return this._pointerX;
  16177. },
  16178. enumerable: true,
  16179. configurable: true
  16180. });
  16181. Object.defineProperty(Scene.prototype, "pointerY", {
  16182. /**
  16183. * Current on-screen Y position of the pointer
  16184. * @return {number} Y position of the pointer
  16185. */
  16186. get: function () {
  16187. return this._pointerY;
  16188. },
  16189. enumerable: true,
  16190. configurable: true
  16191. });
  16192. Scene.prototype.getCachedMaterial = function () {
  16193. return this._cachedMaterial;
  16194. };
  16195. Scene.prototype.getCachedEffect = function () {
  16196. return this._cachedEffect;
  16197. };
  16198. Scene.prototype.getCachedVisibility = function () {
  16199. return this._cachedVisibility;
  16200. };
  16201. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  16202. if (visibility === void 0) { visibility = 0; }
  16203. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16204. };
  16205. Scene.prototype.getBoundingBoxRenderer = function () {
  16206. if (!this._boundingBoxRenderer) {
  16207. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16208. }
  16209. return this._boundingBoxRenderer;
  16210. };
  16211. Scene.prototype.getOutlineRenderer = function () {
  16212. return this._outlineRenderer;
  16213. };
  16214. Scene.prototype.getEngine = function () {
  16215. return this._engine;
  16216. };
  16217. Scene.prototype.getTotalVertices = function () {
  16218. return this._totalVertices.current;
  16219. };
  16220. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16221. get: function () {
  16222. return this._totalVertices;
  16223. },
  16224. enumerable: true,
  16225. configurable: true
  16226. });
  16227. Scene.prototype.getActiveIndices = function () {
  16228. return this._activeIndices.current;
  16229. };
  16230. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16231. get: function () {
  16232. return this._activeIndices;
  16233. },
  16234. enumerable: true,
  16235. configurable: true
  16236. });
  16237. Scene.prototype.getActiveParticles = function () {
  16238. return this._activeParticles.current;
  16239. };
  16240. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16241. get: function () {
  16242. return this._activeParticles;
  16243. },
  16244. enumerable: true,
  16245. configurable: true
  16246. });
  16247. Scene.prototype.getActiveBones = function () {
  16248. return this._activeBones.current;
  16249. };
  16250. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16251. get: function () {
  16252. return this._activeBones;
  16253. },
  16254. enumerable: true,
  16255. configurable: true
  16256. });
  16257. // Stats
  16258. Scene.prototype.getLastFrameDuration = function () {
  16259. return this._lastFrameDuration.current;
  16260. };
  16261. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16262. get: function () {
  16263. return this._lastFrameDuration;
  16264. },
  16265. enumerable: true,
  16266. configurable: true
  16267. });
  16268. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16269. return this._evaluateActiveMeshesDuration.current;
  16270. };
  16271. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16272. get: function () {
  16273. return this._evaluateActiveMeshesDuration;
  16274. },
  16275. enumerable: true,
  16276. configurable: true
  16277. });
  16278. Scene.prototype.getActiveMeshes = function () {
  16279. return this._activeMeshes;
  16280. };
  16281. Scene.prototype.getRenderTargetsDuration = function () {
  16282. return this._renderTargetsDuration.current;
  16283. };
  16284. Scene.prototype.getRenderDuration = function () {
  16285. return this._renderDuration.current;
  16286. };
  16287. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16288. get: function () {
  16289. return this._renderDuration;
  16290. },
  16291. enumerable: true,
  16292. configurable: true
  16293. });
  16294. Scene.prototype.getParticlesDuration = function () {
  16295. return this._particlesDuration.current;
  16296. };
  16297. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16298. get: function () {
  16299. return this._particlesDuration;
  16300. },
  16301. enumerable: true,
  16302. configurable: true
  16303. });
  16304. Scene.prototype.getSpritesDuration = function () {
  16305. return this._spritesDuration.current;
  16306. };
  16307. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16308. get: function () {
  16309. return this._spritesDuration;
  16310. },
  16311. enumerable: true,
  16312. configurable: true
  16313. });
  16314. Scene.prototype.getAnimationRatio = function () {
  16315. return this._animationRatio;
  16316. };
  16317. Scene.prototype.getRenderId = function () {
  16318. return this._renderId;
  16319. };
  16320. Scene.prototype.incrementRenderId = function () {
  16321. this._renderId++;
  16322. };
  16323. Scene.prototype._updatePointerPosition = function (evt) {
  16324. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16325. this._pointerX = evt.clientX - canvasRect.left;
  16326. this._pointerY = evt.clientY - canvasRect.top;
  16327. this._unTranslatedPointerX = this._pointerX;
  16328. this._unTranslatedPointerY = this._pointerY;
  16329. if (this.cameraToUseForPointers) {
  16330. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16331. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16332. }
  16333. };
  16334. Scene.prototype._createUbo = function () {
  16335. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16336. this._sceneUbo.addUniform("viewProjection", 16);
  16337. this._sceneUbo.addUniform("view", 16);
  16338. };
  16339. // Pointers handling
  16340. /**
  16341. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16342. * @param attachUp defines if you want to attach events to pointerup
  16343. * @param attachDown defines if you want to attach events to pointerdown
  16344. * @param attachMove defines if you want to attach events to pointermove
  16345. */
  16346. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16347. var _this = this;
  16348. if (attachUp === void 0) { attachUp = true; }
  16349. if (attachDown === void 0) { attachDown = true; }
  16350. if (attachMove === void 0) { attachMove = true; }
  16351. this._initActionManager = function (act, clickInfo) {
  16352. if (!_this._meshPickProceed) {
  16353. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16354. _this._currentPickResult = pickResult;
  16355. if (pickResult) {
  16356. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16357. }
  16358. _this._meshPickProceed = true;
  16359. }
  16360. return act;
  16361. };
  16362. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16363. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16364. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16365. btn !== _this._previousButtonPressed) {
  16366. _this._doubleClickOccured = false;
  16367. clickInfo.singleClick = true;
  16368. clickInfo.ignore = false;
  16369. cb(clickInfo, _this._currentPickResult);
  16370. }
  16371. };
  16372. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16373. var clickInfo = new ClickInfo();
  16374. _this._currentPickResult = null;
  16375. var act;
  16376. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16377. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16378. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16379. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16380. act = _this._initActionManager(act, clickInfo);
  16381. if (act)
  16382. checkPicking = act.hasPickTriggers;
  16383. }
  16384. if (checkPicking) {
  16385. var btn = evt.button;
  16386. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16387. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16388. if (!clickInfo.hasSwiped) {
  16389. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16390. if (!checkSingleClickImmediately) {
  16391. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16392. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16393. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16394. act = _this._initActionManager(act, clickInfo);
  16395. if (act)
  16396. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16397. }
  16398. }
  16399. if (checkSingleClickImmediately) {
  16400. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16401. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16402. btn !== _this._previousButtonPressed) {
  16403. clickInfo.singleClick = true;
  16404. cb(clickInfo, _this._currentPickResult);
  16405. }
  16406. }
  16407. else {
  16408. // wait that no double click has been raised during the double click delay
  16409. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16410. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16411. }
  16412. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16413. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16414. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16415. act = _this._initActionManager(act, clickInfo);
  16416. if (act)
  16417. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16418. }
  16419. if (checkDoubleClick) {
  16420. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16421. if (btn === _this._previousButtonPressed &&
  16422. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16423. !_this._doubleClickOccured) {
  16424. // pointer has not moved for 2 clicks, it's a double click
  16425. if (!clickInfo.hasSwiped &&
  16426. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16427. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16428. _this._previousStartingPointerTime = 0;
  16429. _this._doubleClickOccured = true;
  16430. clickInfo.doubleClick = true;
  16431. clickInfo.ignore = false;
  16432. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16433. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16434. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16435. cb(clickInfo, _this._currentPickResult);
  16436. }
  16437. else {
  16438. _this._doubleClickOccured = false;
  16439. _this._previousStartingPointerTime = _this._startingPointerTime;
  16440. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16441. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16442. _this._previousButtonPressed = btn;
  16443. _this._previousHasSwiped = clickInfo.hasSwiped;
  16444. if (Scene.ExclusiveDoubleClickMode) {
  16445. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16446. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16447. }
  16448. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16449. cb(clickInfo, _this._previousPickResult);
  16450. }
  16451. else {
  16452. cb(clickInfo, _this._currentPickResult);
  16453. }
  16454. }
  16455. }
  16456. else {
  16457. _this._doubleClickOccured = false;
  16458. _this._previousStartingPointerTime = _this._startingPointerTime;
  16459. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16460. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16461. _this._previousButtonPressed = btn;
  16462. _this._previousHasSwiped = clickInfo.hasSwiped;
  16463. }
  16464. }
  16465. }
  16466. }
  16467. clickInfo.ignore = true;
  16468. cb(clickInfo, _this._currentPickResult);
  16469. };
  16470. var spritePredicate = function (sprite) {
  16471. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16472. };
  16473. this._onPointerMove = function (evt) {
  16474. _this._updatePointerPosition(evt);
  16475. // PreObservable support
  16476. if (_this.onPrePointerObservable.hasObservers()) {
  16477. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16478. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16479. _this.onPrePointerObservable.notifyObservers(pi, type);
  16480. if (pi.skipOnPointerObservable) {
  16481. return;
  16482. }
  16483. }
  16484. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16485. return;
  16486. }
  16487. var canvas = _this._engine.getRenderingCanvas();
  16488. if (!_this.pointerMovePredicate) {
  16489. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16490. }
  16491. // Meshes
  16492. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16493. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16494. _this.setPointerOverSprite(null);
  16495. _this.setPointerOverMesh(pickResult.pickedMesh);
  16496. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16497. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16498. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16499. }
  16500. else {
  16501. canvas.style.cursor = _this.hoverCursor;
  16502. }
  16503. }
  16504. else {
  16505. canvas.style.cursor = "";
  16506. }
  16507. }
  16508. else {
  16509. _this.setPointerOverMesh(null);
  16510. // Sprites
  16511. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16512. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16513. _this.setPointerOverSprite(pickResult.pickedSprite);
  16514. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16515. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16516. }
  16517. else {
  16518. canvas.style.cursor = _this.hoverCursor;
  16519. }
  16520. }
  16521. else {
  16522. _this.setPointerOverSprite(null);
  16523. // Restore pointer
  16524. canvas.style.cursor = "";
  16525. }
  16526. }
  16527. if (_this.onPointerMove) {
  16528. _this.onPointerMove(evt, pickResult);
  16529. }
  16530. if (_this.onPointerObservable.hasObservers()) {
  16531. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16532. var pi = new PointerInfo(type, evt, pickResult);
  16533. _this.onPointerObservable.notifyObservers(pi, type);
  16534. }
  16535. };
  16536. this._onPointerDown = function (evt) {
  16537. _this._isButtonPressed = true;
  16538. _this._pickedDownMesh = null;
  16539. _this._meshPickProceed = false;
  16540. _this._updatePointerPosition(evt);
  16541. // PreObservable support
  16542. if (_this.onPrePointerObservable.hasObservers()) {
  16543. var type = PointerEventTypes.POINTERDOWN;
  16544. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16545. _this.onPrePointerObservable.notifyObservers(pi, type);
  16546. if (pi.skipOnPointerObservable) {
  16547. return;
  16548. }
  16549. }
  16550. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16551. return;
  16552. }
  16553. _this._startingPointerPosition.x = _this._pointerX;
  16554. _this._startingPointerPosition.y = _this._pointerY;
  16555. _this._startingPointerTime = new Date().getTime();
  16556. if (!_this.pointerDownPredicate) {
  16557. _this.pointerDownPredicate = function (mesh) {
  16558. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16559. };
  16560. }
  16561. // Meshes
  16562. _this._pickedDownMesh = null;
  16563. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16564. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16565. _this._pickedDownMesh = pickResult.pickedMesh;
  16566. var actionManager = pickResult.pickedMesh.actionManager;
  16567. if (actionManager) {
  16568. if (actionManager.hasPickTriggers) {
  16569. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16570. switch (evt.button) {
  16571. case 0:
  16572. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16573. break;
  16574. case 1:
  16575. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16576. break;
  16577. case 2:
  16578. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16579. break;
  16580. }
  16581. }
  16582. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16583. window.setTimeout((function () {
  16584. var _this = this;
  16585. 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);
  16586. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16587. if (this._isButtonPressed &&
  16588. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16589. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16590. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16591. this._startingPointerTime = 0;
  16592. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16593. }
  16594. }
  16595. }).bind(_this), Scene.LongPressDelay);
  16596. }
  16597. }
  16598. }
  16599. if (_this.onPointerDown) {
  16600. _this.onPointerDown(evt, pickResult);
  16601. }
  16602. if (_this.onPointerObservable.hasObservers()) {
  16603. var type = PointerEventTypes.POINTERDOWN;
  16604. var pi = new PointerInfo(type, evt, pickResult);
  16605. _this.onPointerObservable.notifyObservers(pi, type);
  16606. }
  16607. // Sprites
  16608. _this._pickedDownSprite = null;
  16609. if (_this.spriteManagers.length > 0) {
  16610. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16611. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16612. if (pickResult.pickedSprite.actionManager) {
  16613. _this._pickedDownSprite = pickResult.pickedSprite;
  16614. switch (evt.button) {
  16615. case 0:
  16616. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16617. break;
  16618. case 1:
  16619. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16620. break;
  16621. case 2:
  16622. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16623. break;
  16624. }
  16625. if (pickResult.pickedSprite.actionManager) {
  16626. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16627. }
  16628. }
  16629. }
  16630. }
  16631. };
  16632. this._onPointerUp = function (evt) {
  16633. _this._isButtonPressed = false;
  16634. _this._pickedUpMesh = null;
  16635. _this._meshPickProceed = false;
  16636. _this._updatePointerPosition(evt);
  16637. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16638. // PreObservable support
  16639. if (this.onPrePointerObservable.hasObservers()) {
  16640. if (!clickInfo.ignore) {
  16641. if (!clickInfo.hasSwiped) {
  16642. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16643. var type = PointerEventTypes.POINTERTAP;
  16644. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16645. this.onPrePointerObservable.notifyObservers(pi, type);
  16646. if (pi.skipOnPointerObservable) {
  16647. return;
  16648. }
  16649. }
  16650. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16651. var type = PointerEventTypes.POINTERDOUBLETAP;
  16652. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16653. this.onPrePointerObservable.notifyObservers(pi, type);
  16654. if (pi.skipOnPointerObservable) {
  16655. return;
  16656. }
  16657. }
  16658. }
  16659. }
  16660. else {
  16661. var type = PointerEventTypes.POINTERUP;
  16662. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16663. this.onPrePointerObservable.notifyObservers(pi, type);
  16664. if (pi.skipOnPointerObservable) {
  16665. return;
  16666. }
  16667. }
  16668. }
  16669. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16670. return;
  16671. }
  16672. if (!this.pointerUpPredicate) {
  16673. this.pointerUpPredicate = function (mesh) {
  16674. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16675. };
  16676. }
  16677. // Meshes
  16678. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16679. this._initActionManager(null, clickInfo);
  16680. }
  16681. if (!pickResult) {
  16682. pickResult = this._currentPickResult;
  16683. }
  16684. if (pickResult && pickResult && pickResult.pickedMesh) {
  16685. this._pickedUpMesh = pickResult.pickedMesh;
  16686. if (this._pickedDownMesh === this._pickedUpMesh) {
  16687. if (this.onPointerPick) {
  16688. this.onPointerPick(evt, pickResult);
  16689. }
  16690. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16691. var type = PointerEventTypes.POINTERPICK;
  16692. var pi = new PointerInfo(type, evt, pickResult);
  16693. this.onPointerObservable.notifyObservers(pi, type);
  16694. }
  16695. }
  16696. if (pickResult.pickedMesh.actionManager) {
  16697. if (clickInfo.ignore) {
  16698. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16699. }
  16700. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16701. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16702. }
  16703. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16704. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16705. }
  16706. }
  16707. }
  16708. if (this._pickedDownMesh &&
  16709. this._pickedDownMesh.actionManager &&
  16710. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16711. this._pickedDownMesh !== this._pickedUpMesh) {
  16712. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16713. }
  16714. if (this.onPointerUp) {
  16715. this.onPointerUp(evt, pickResult);
  16716. }
  16717. if (this.onPointerObservable.hasObservers()) {
  16718. if (!clickInfo.ignore) {
  16719. if (!clickInfo.hasSwiped) {
  16720. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16721. var type = PointerEventTypes.POINTERTAP;
  16722. var pi = new PointerInfo(type, evt, pickResult);
  16723. this.onPointerObservable.notifyObservers(pi, type);
  16724. }
  16725. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16726. var type = PointerEventTypes.POINTERDOUBLETAP;
  16727. var pi = new PointerInfo(type, evt, pickResult);
  16728. this.onPointerObservable.notifyObservers(pi, type);
  16729. }
  16730. }
  16731. }
  16732. else {
  16733. var type = PointerEventTypes.POINTERUP;
  16734. var pi = new PointerInfo(type, evt, pickResult);
  16735. this.onPointerObservable.notifyObservers(pi, type);
  16736. }
  16737. }
  16738. // Sprites
  16739. if (this.spriteManagers.length > 0) {
  16740. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16741. if (pickResult.hit && pickResult.pickedSprite) {
  16742. if (pickResult.pickedSprite.actionManager) {
  16743. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16744. if (pickResult.pickedSprite.actionManager) {
  16745. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16746. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16747. }
  16748. }
  16749. }
  16750. }
  16751. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16752. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16753. }
  16754. }
  16755. this._previousPickResult = this._currentPickResult;
  16756. }).bind(_this));
  16757. };
  16758. this._onKeyDown = function (evt) {
  16759. if (_this.actionManager) {
  16760. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16761. }
  16762. };
  16763. this._onKeyUp = function (evt) {
  16764. if (_this.actionManager) {
  16765. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16766. }
  16767. };
  16768. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16769. var canvas = this._engine.getRenderingCanvas();
  16770. if (attachMove) {
  16771. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16772. // Wheel
  16773. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16774. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16775. }
  16776. if (attachDown) {
  16777. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16778. }
  16779. if (attachUp) {
  16780. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16781. }
  16782. canvas.tabIndex = 1;
  16783. canvas.addEventListener("keydown", this._onKeyDown, false);
  16784. canvas.addEventListener("keyup", this._onKeyUp, false);
  16785. };
  16786. Scene.prototype.detachControl = function () {
  16787. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16788. var canvas = this._engine.getRenderingCanvas();
  16789. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16790. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16791. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16792. // Wheel
  16793. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16794. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16795. canvas.removeEventListener("keydown", this._onKeyDown);
  16796. canvas.removeEventListener("keyup", this._onKeyUp);
  16797. };
  16798. // Ready
  16799. Scene.prototype.isReady = function () {
  16800. if (this._pendingData.length > 0) {
  16801. return false;
  16802. }
  16803. var index;
  16804. // Geometries
  16805. for (index = 0; index < this._geometries.length; index++) {
  16806. var geometry = this._geometries[index];
  16807. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16808. return false;
  16809. }
  16810. }
  16811. // Meshes
  16812. for (index = 0; index < this.meshes.length; index++) {
  16813. var mesh = this.meshes[index];
  16814. if (!mesh.isEnabled()) {
  16815. continue;
  16816. }
  16817. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16818. continue;
  16819. }
  16820. if (!mesh.isReady()) {
  16821. return false;
  16822. }
  16823. var mat = mesh.material;
  16824. if (mat) {
  16825. if (!mat.isReady(mesh)) {
  16826. return false;
  16827. }
  16828. }
  16829. }
  16830. return true;
  16831. };
  16832. Scene.prototype.resetCachedMaterial = function () {
  16833. this._cachedMaterial = null;
  16834. this._cachedEffect = null;
  16835. this._cachedVisibility = null;
  16836. };
  16837. Scene.prototype.registerBeforeRender = function (func) {
  16838. this.onBeforeRenderObservable.add(func);
  16839. };
  16840. Scene.prototype.unregisterBeforeRender = function (func) {
  16841. this.onBeforeRenderObservable.removeCallback(func);
  16842. };
  16843. Scene.prototype.registerAfterRender = function (func) {
  16844. this.onAfterRenderObservable.add(func);
  16845. };
  16846. Scene.prototype.unregisterAfterRender = function (func) {
  16847. this.onAfterRenderObservable.removeCallback(func);
  16848. };
  16849. Scene.prototype._addPendingData = function (data) {
  16850. this._pendingData.push(data);
  16851. };
  16852. Scene.prototype._removePendingData = function (data) {
  16853. var index = this._pendingData.indexOf(data);
  16854. if (index !== -1) {
  16855. this._pendingData.splice(index, 1);
  16856. }
  16857. };
  16858. Scene.prototype.getWaitingItemsCount = function () {
  16859. return this._pendingData.length;
  16860. };
  16861. /**
  16862. * Registers a function to be executed when the scene is ready.
  16863. * @param {Function} func - the function to be executed.
  16864. */
  16865. Scene.prototype.executeWhenReady = function (func) {
  16866. var _this = this;
  16867. this.onReadyObservable.add(func);
  16868. if (this._executeWhenReadyTimeoutId !== -1) {
  16869. return;
  16870. }
  16871. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16872. _this._checkIsReady();
  16873. }, 150);
  16874. };
  16875. Scene.prototype._checkIsReady = function () {
  16876. var _this = this;
  16877. if (this.isReady()) {
  16878. this.onReadyObservable.notifyObservers(this);
  16879. this.onReadyObservable.clear();
  16880. this._executeWhenReadyTimeoutId = -1;
  16881. return;
  16882. }
  16883. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16884. _this._checkIsReady();
  16885. }, 150);
  16886. };
  16887. // Animations
  16888. /**
  16889. * Will start the animation sequence of a given target
  16890. * @param target - the target
  16891. * @param {number} from - from which frame should animation start
  16892. * @param {number} to - till which frame should animation run.
  16893. * @param {boolean} [loop] - should the animation loop
  16894. * @param {number} [speedRatio] - the speed in which to run the animation
  16895. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16896. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16897. * @return {BABYLON.Animatable} the animatable object created for this animation
  16898. * @see BABYLON.Animatable
  16899. * @see http://doc.babylonjs.com/page.php?p=22081
  16900. */
  16901. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16902. if (speedRatio === void 0) { speedRatio = 1.0; }
  16903. if (from > to && speedRatio > 0) {
  16904. speedRatio *= -1;
  16905. }
  16906. this.stopAnimation(target);
  16907. if (!animatable) {
  16908. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16909. }
  16910. // Local animations
  16911. if (target.animations) {
  16912. animatable.appendAnimations(target, target.animations);
  16913. }
  16914. // Children animations
  16915. if (target.getAnimatables) {
  16916. var animatables = target.getAnimatables();
  16917. for (var index = 0; index < animatables.length; index++) {
  16918. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16919. }
  16920. }
  16921. animatable.reset();
  16922. return animatable;
  16923. };
  16924. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16925. if (speedRatio === undefined) {
  16926. speedRatio = 1.0;
  16927. }
  16928. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16929. return animatable;
  16930. };
  16931. Scene.prototype.getAnimatableByTarget = function (target) {
  16932. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16933. if (this._activeAnimatables[index].target === target) {
  16934. return this._activeAnimatables[index];
  16935. }
  16936. }
  16937. return null;
  16938. };
  16939. Object.defineProperty(Scene.prototype, "Animatables", {
  16940. get: function () {
  16941. return this._activeAnimatables;
  16942. },
  16943. enumerable: true,
  16944. configurable: true
  16945. });
  16946. /**
  16947. * Will stop the animation of the given target
  16948. * @param target - the target
  16949. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16950. * @see beginAnimation
  16951. */
  16952. Scene.prototype.stopAnimation = function (target, animationName) {
  16953. var animatable = this.getAnimatableByTarget(target);
  16954. if (animatable) {
  16955. animatable.stop(animationName);
  16956. }
  16957. };
  16958. Scene.prototype._animate = function () {
  16959. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16960. return;
  16961. }
  16962. // Getting time
  16963. var now = BABYLON.Tools.Now;
  16964. if (!this._animationTimeLast) {
  16965. if (this._pendingData.length > 0) {
  16966. return;
  16967. }
  16968. this._animationTimeLast = now;
  16969. }
  16970. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16971. this._animationTime += deltaTime;
  16972. this._animationTimeLast = now;
  16973. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16974. this._activeAnimatables[index]._animate(this._animationTime);
  16975. }
  16976. };
  16977. // Matrix
  16978. Scene.prototype.getViewMatrix = function () {
  16979. return this._viewMatrix;
  16980. };
  16981. Scene.prototype.getProjectionMatrix = function () {
  16982. return this._projectionMatrix;
  16983. };
  16984. Scene.prototype.getTransformMatrix = function () {
  16985. return this._transformMatrix;
  16986. };
  16987. Scene.prototype.setTransformMatrix = function (view, projection) {
  16988. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16989. return;
  16990. }
  16991. this._viewUpdateFlag = view.updateFlag;
  16992. this._projectionUpdateFlag = projection.updateFlag;
  16993. this._viewMatrix = view;
  16994. this._projectionMatrix = projection;
  16995. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16996. // Update frustum
  16997. if (!this._frustumPlanes) {
  16998. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16999. }
  17000. else {
  17001. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17002. }
  17003. if (this._sceneUbo.useUbo) {
  17004. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17005. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17006. this._sceneUbo.update();
  17007. }
  17008. };
  17009. Scene.prototype.getSceneUniformBuffer = function () {
  17010. return this._sceneUbo;
  17011. };
  17012. // Methods
  17013. Scene.prototype.getUniqueId = function () {
  17014. var result = this._uniqueIdCounter;
  17015. this._uniqueIdCounter++;
  17016. return result;
  17017. };
  17018. Scene.prototype.addMesh = function (newMesh) {
  17019. newMesh.uniqueId = this.getUniqueId();
  17020. var position = this.meshes.push(newMesh);
  17021. //notify the collision coordinator
  17022. if (this.collisionCoordinator) {
  17023. this.collisionCoordinator.onMeshAdded(newMesh);
  17024. }
  17025. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17026. };
  17027. Scene.prototype.removeMesh = function (toRemove) {
  17028. var index = this.meshes.indexOf(toRemove);
  17029. if (index !== -1) {
  17030. // Remove from the scene if mesh found
  17031. this.meshes.splice(index, 1);
  17032. }
  17033. //notify the collision coordinator
  17034. if (this.collisionCoordinator) {
  17035. this.collisionCoordinator.onMeshRemoved(toRemove);
  17036. }
  17037. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17038. return index;
  17039. };
  17040. Scene.prototype.removeSkeleton = function (toRemove) {
  17041. var index = this.skeletons.indexOf(toRemove);
  17042. if (index !== -1) {
  17043. // Remove from the scene if found
  17044. this.skeletons.splice(index, 1);
  17045. }
  17046. return index;
  17047. };
  17048. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17049. var index = this.morphTargetManagers.indexOf(toRemove);
  17050. if (index !== -1) {
  17051. // Remove from the scene if found
  17052. this.morphTargetManagers.splice(index, 1);
  17053. }
  17054. return index;
  17055. };
  17056. Scene.prototype.removeLight = function (toRemove) {
  17057. var index = this.lights.indexOf(toRemove);
  17058. if (index !== -1) {
  17059. // Remove from the scene if mesh found
  17060. this.lights.splice(index, 1);
  17061. this.sortLightsByPriority();
  17062. }
  17063. this.onLightRemovedObservable.notifyObservers(toRemove);
  17064. return index;
  17065. };
  17066. Scene.prototype.removeCamera = function (toRemove) {
  17067. var index = this.cameras.indexOf(toRemove);
  17068. if (index !== -1) {
  17069. // Remove from the scene if mesh found
  17070. this.cameras.splice(index, 1);
  17071. }
  17072. // Remove from activeCameras
  17073. var index2 = this.activeCameras.indexOf(toRemove);
  17074. if (index2 !== -1) {
  17075. // Remove from the scene if mesh found
  17076. this.activeCameras.splice(index2, 1);
  17077. }
  17078. // Reset the activeCamera
  17079. if (this.activeCamera === toRemove) {
  17080. if (this.cameras.length > 0) {
  17081. this.activeCamera = this.cameras[0];
  17082. }
  17083. else {
  17084. this.activeCamera = null;
  17085. }
  17086. }
  17087. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17088. return index;
  17089. };
  17090. Scene.prototype.addLight = function (newLight) {
  17091. newLight.uniqueId = this.getUniqueId();
  17092. this.lights.push(newLight);
  17093. this.sortLightsByPriority();
  17094. this.onNewLightAddedObservable.notifyObservers(newLight);
  17095. };
  17096. Scene.prototype.sortLightsByPriority = function () {
  17097. if (this.requireLightSorting) {
  17098. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17099. }
  17100. };
  17101. Scene.prototype.addCamera = function (newCamera) {
  17102. newCamera.uniqueId = this.getUniqueId();
  17103. var position = this.cameras.push(newCamera);
  17104. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17105. };
  17106. /**
  17107. * Switch active camera
  17108. * @param {Camera} newCamera - new active camera
  17109. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17110. */
  17111. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17112. if (attachControl === void 0) { attachControl = true; }
  17113. var canvas = this._engine.getRenderingCanvas();
  17114. this.activeCamera.detachControl(canvas);
  17115. this.activeCamera = newCamera;
  17116. if (attachControl) {
  17117. newCamera.attachControl(canvas);
  17118. }
  17119. };
  17120. /**
  17121. * sets the active camera of the scene using its ID
  17122. * @param {string} id - the camera's ID
  17123. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17124. * @see activeCamera
  17125. */
  17126. Scene.prototype.setActiveCameraByID = function (id) {
  17127. var camera = this.getCameraByID(id);
  17128. if (camera) {
  17129. this.activeCamera = camera;
  17130. return camera;
  17131. }
  17132. return null;
  17133. };
  17134. /**
  17135. * sets the active camera of the scene using its name
  17136. * @param {string} name - the camera's name
  17137. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17138. * @see activeCamera
  17139. */
  17140. Scene.prototype.setActiveCameraByName = function (name) {
  17141. var camera = this.getCameraByName(name);
  17142. if (camera) {
  17143. this.activeCamera = camera;
  17144. return camera;
  17145. }
  17146. return null;
  17147. };
  17148. /**
  17149. * get a material using its id
  17150. * @param {string} the material's ID
  17151. * @return {BABYLON.Material|null} the material or null if none found.
  17152. */
  17153. Scene.prototype.getMaterialByID = function (id) {
  17154. for (var index = 0; index < this.materials.length; index++) {
  17155. if (this.materials[index].id === id) {
  17156. return this.materials[index];
  17157. }
  17158. }
  17159. return null;
  17160. };
  17161. /**
  17162. * get a material using its name
  17163. * @param {string} the material's name
  17164. * @return {BABYLON.Material|null} the material or null if none found.
  17165. */
  17166. Scene.prototype.getMaterialByName = function (name) {
  17167. for (var index = 0; index < this.materials.length; index++) {
  17168. if (this.materials[index].name === name) {
  17169. return this.materials[index];
  17170. }
  17171. }
  17172. return null;
  17173. };
  17174. Scene.prototype.getLensFlareSystemByName = function (name) {
  17175. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17176. if (this.lensFlareSystems[index].name === name) {
  17177. return this.lensFlareSystems[index];
  17178. }
  17179. }
  17180. return null;
  17181. };
  17182. Scene.prototype.getLensFlareSystemByID = function (id) {
  17183. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17184. if (this.lensFlareSystems[index].id === id) {
  17185. return this.lensFlareSystems[index];
  17186. }
  17187. }
  17188. return null;
  17189. };
  17190. Scene.prototype.getCameraByID = function (id) {
  17191. for (var index = 0; index < this.cameras.length; index++) {
  17192. if (this.cameras[index].id === id) {
  17193. return this.cameras[index];
  17194. }
  17195. }
  17196. return null;
  17197. };
  17198. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17199. for (var index = 0; index < this.cameras.length; index++) {
  17200. if (this.cameras[index].uniqueId === uniqueId) {
  17201. return this.cameras[index];
  17202. }
  17203. }
  17204. return null;
  17205. };
  17206. /**
  17207. * get a camera using its name
  17208. * @param {string} the camera's name
  17209. * @return {BABYLON.Camera|null} the camera or null if none found.
  17210. */
  17211. Scene.prototype.getCameraByName = function (name) {
  17212. for (var index = 0; index < this.cameras.length; index++) {
  17213. if (this.cameras[index].name === name) {
  17214. return this.cameras[index];
  17215. }
  17216. }
  17217. return null;
  17218. };
  17219. /**
  17220. * get a bone using its id
  17221. * @param {string} the bone's id
  17222. * @return {BABYLON.Bone|null} the bone or null if not found
  17223. */
  17224. Scene.prototype.getBoneByID = function (id) {
  17225. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17226. var skeleton = this.skeletons[skeletonIndex];
  17227. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17228. if (skeleton.bones[boneIndex].id === id) {
  17229. return skeleton.bones[boneIndex];
  17230. }
  17231. }
  17232. }
  17233. return null;
  17234. };
  17235. /**
  17236. * get a bone using its id
  17237. * @param {string} the bone's name
  17238. * @return {BABYLON.Bone|null} the bone or null if not found
  17239. */
  17240. Scene.prototype.getBoneByName = function (name) {
  17241. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17242. var skeleton = this.skeletons[skeletonIndex];
  17243. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17244. if (skeleton.bones[boneIndex].name === name) {
  17245. return skeleton.bones[boneIndex];
  17246. }
  17247. }
  17248. }
  17249. return null;
  17250. };
  17251. /**
  17252. * get a light node using its name
  17253. * @param {string} the light's name
  17254. * @return {BABYLON.Light|null} the light or null if none found.
  17255. */
  17256. Scene.prototype.getLightByName = function (name) {
  17257. for (var index = 0; index < this.lights.length; index++) {
  17258. if (this.lights[index].name === name) {
  17259. return this.lights[index];
  17260. }
  17261. }
  17262. return null;
  17263. };
  17264. /**
  17265. * get a light node using its ID
  17266. * @param {string} the light's id
  17267. * @return {BABYLON.Light|null} the light or null if none found.
  17268. */
  17269. Scene.prototype.getLightByID = function (id) {
  17270. for (var index = 0; index < this.lights.length; index++) {
  17271. if (this.lights[index].id === id) {
  17272. return this.lights[index];
  17273. }
  17274. }
  17275. return null;
  17276. };
  17277. /**
  17278. * get a light node using its scene-generated unique ID
  17279. * @param {number} the light's unique id
  17280. * @return {BABYLON.Light|null} the light or null if none found.
  17281. */
  17282. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17283. for (var index = 0; index < this.lights.length; index++) {
  17284. if (this.lights[index].uniqueId === uniqueId) {
  17285. return this.lights[index];
  17286. }
  17287. }
  17288. return null;
  17289. };
  17290. /**
  17291. * get a particle system by id
  17292. * @param id {number} the particle system id
  17293. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17294. */
  17295. Scene.prototype.getParticleSystemByID = function (id) {
  17296. for (var index = 0; index < this.particleSystems.length; index++) {
  17297. if (this.particleSystems[index].id === id) {
  17298. return this.particleSystems[index];
  17299. }
  17300. }
  17301. return null;
  17302. };
  17303. /**
  17304. * get a geometry using its ID
  17305. * @param {string} the geometry's id
  17306. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17307. */
  17308. Scene.prototype.getGeometryByID = function (id) {
  17309. for (var index = 0; index < this._geometries.length; index++) {
  17310. if (this._geometries[index].id === id) {
  17311. return this._geometries[index];
  17312. }
  17313. }
  17314. return null;
  17315. };
  17316. /**
  17317. * add a new geometry to this scene.
  17318. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17319. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17320. * @return {boolean} was the geometry added or not
  17321. */
  17322. Scene.prototype.pushGeometry = function (geometry, force) {
  17323. if (!force && this.getGeometryByID(geometry.id)) {
  17324. return false;
  17325. }
  17326. this._geometries.push(geometry);
  17327. //notify the collision coordinator
  17328. if (this.collisionCoordinator) {
  17329. this.collisionCoordinator.onGeometryAdded(geometry);
  17330. }
  17331. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17332. return true;
  17333. };
  17334. /**
  17335. * Removes an existing geometry
  17336. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17337. * @return {boolean} was the geometry removed or not
  17338. */
  17339. Scene.prototype.removeGeometry = function (geometry) {
  17340. var index = this._geometries.indexOf(geometry);
  17341. if (index > -1) {
  17342. this._geometries.splice(index, 1);
  17343. //notify the collision coordinator
  17344. if (this.collisionCoordinator) {
  17345. this.collisionCoordinator.onGeometryDeleted(geometry);
  17346. }
  17347. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17348. return true;
  17349. }
  17350. return false;
  17351. };
  17352. Scene.prototype.getGeometries = function () {
  17353. return this._geometries;
  17354. };
  17355. /**
  17356. * Get the first added mesh found of a given ID
  17357. * @param {string} id - the id to search for
  17358. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17359. */
  17360. Scene.prototype.getMeshByID = function (id) {
  17361. for (var index = 0; index < this.meshes.length; index++) {
  17362. if (this.meshes[index].id === id) {
  17363. return this.meshes[index];
  17364. }
  17365. }
  17366. return null;
  17367. };
  17368. Scene.prototype.getMeshesByID = function (id) {
  17369. return this.meshes.filter(function (m) {
  17370. return m.id === id;
  17371. });
  17372. };
  17373. /**
  17374. * Get a mesh with its auto-generated unique id
  17375. * @param {number} uniqueId - the unique id to search for
  17376. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17377. */
  17378. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17379. for (var index = 0; index < this.meshes.length; index++) {
  17380. if (this.meshes[index].uniqueId === uniqueId) {
  17381. return this.meshes[index];
  17382. }
  17383. }
  17384. return null;
  17385. };
  17386. /**
  17387. * Get a the last added mesh found of a given ID
  17388. * @param {string} id - the id to search for
  17389. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17390. */
  17391. Scene.prototype.getLastMeshByID = function (id) {
  17392. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17393. if (this.meshes[index].id === id) {
  17394. return this.meshes[index];
  17395. }
  17396. }
  17397. return null;
  17398. };
  17399. /**
  17400. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17401. * @param {string} id - the id to search for
  17402. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17403. */
  17404. Scene.prototype.getLastEntryByID = function (id) {
  17405. var index;
  17406. for (index = this.meshes.length - 1; index >= 0; index--) {
  17407. if (this.meshes[index].id === id) {
  17408. return this.meshes[index];
  17409. }
  17410. }
  17411. for (index = this.cameras.length - 1; index >= 0; index--) {
  17412. if (this.cameras[index].id === id) {
  17413. return this.cameras[index];
  17414. }
  17415. }
  17416. for (index = this.lights.length - 1; index >= 0; index--) {
  17417. if (this.lights[index].id === id) {
  17418. return this.lights[index];
  17419. }
  17420. }
  17421. return null;
  17422. };
  17423. Scene.prototype.getNodeByID = function (id) {
  17424. var mesh = this.getMeshByID(id);
  17425. if (mesh) {
  17426. return mesh;
  17427. }
  17428. var light = this.getLightByID(id);
  17429. if (light) {
  17430. return light;
  17431. }
  17432. var camera = this.getCameraByID(id);
  17433. if (camera) {
  17434. return camera;
  17435. }
  17436. var bone = this.getBoneByID(id);
  17437. return bone;
  17438. };
  17439. Scene.prototype.getNodeByName = function (name) {
  17440. var mesh = this.getMeshByName(name);
  17441. if (mesh) {
  17442. return mesh;
  17443. }
  17444. var light = this.getLightByName(name);
  17445. if (light) {
  17446. return light;
  17447. }
  17448. var camera = this.getCameraByName(name);
  17449. if (camera) {
  17450. return camera;
  17451. }
  17452. var bone = this.getBoneByName(name);
  17453. return bone;
  17454. };
  17455. Scene.prototype.getMeshByName = function (name) {
  17456. for (var index = 0; index < this.meshes.length; index++) {
  17457. if (this.meshes[index].name === name) {
  17458. return this.meshes[index];
  17459. }
  17460. }
  17461. return null;
  17462. };
  17463. Scene.prototype.getSoundByName = function (name) {
  17464. var index;
  17465. if (BABYLON.AudioEngine) {
  17466. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17467. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17468. return this.mainSoundTrack.soundCollection[index];
  17469. }
  17470. }
  17471. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17472. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17473. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17474. return this.soundTracks[sdIndex].soundCollection[index];
  17475. }
  17476. }
  17477. }
  17478. }
  17479. return null;
  17480. };
  17481. Scene.prototype.getLastSkeletonByID = function (id) {
  17482. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17483. if (this.skeletons[index].id === id) {
  17484. return this.skeletons[index];
  17485. }
  17486. }
  17487. return null;
  17488. };
  17489. Scene.prototype.getSkeletonById = function (id) {
  17490. for (var index = 0; index < this.skeletons.length; index++) {
  17491. if (this.skeletons[index].id === id) {
  17492. return this.skeletons[index];
  17493. }
  17494. }
  17495. return null;
  17496. };
  17497. Scene.prototype.getSkeletonByName = function (name) {
  17498. for (var index = 0; index < this.skeletons.length; index++) {
  17499. if (this.skeletons[index].name === name) {
  17500. return this.skeletons[index];
  17501. }
  17502. }
  17503. return null;
  17504. };
  17505. Scene.prototype.getMorphTargetManagerById = function (id) {
  17506. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17507. if (this.morphTargetManagers[index].uniqueId === id) {
  17508. return this.morphTargetManagers[index];
  17509. }
  17510. }
  17511. return null;
  17512. };
  17513. Scene.prototype.isActiveMesh = function (mesh) {
  17514. return (this._activeMeshes.indexOf(mesh) !== -1);
  17515. };
  17516. /**
  17517. * Return a the first highlight layer of the scene with a given name.
  17518. * @param name The name of the highlight layer to look for.
  17519. * @return The highlight layer if found otherwise null.
  17520. */
  17521. Scene.prototype.getHighlightLayerByName = function (name) {
  17522. for (var index = 0; index < this.highlightLayers.length; index++) {
  17523. if (this.highlightLayers[index].name === name) {
  17524. return this.highlightLayers[index];
  17525. }
  17526. }
  17527. return null;
  17528. };
  17529. Object.defineProperty(Scene.prototype, "uid", {
  17530. /**
  17531. * Return a unique id as a string which can serve as an identifier for the scene
  17532. */
  17533. get: function () {
  17534. if (!this._uid) {
  17535. this._uid = BABYLON.Tools.RandomId();
  17536. }
  17537. return this._uid;
  17538. },
  17539. enumerable: true,
  17540. configurable: true
  17541. });
  17542. /**
  17543. * Add an externaly attached data from its key.
  17544. * This method call will fail and return false, if such key already exists.
  17545. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17546. * @param key the unique key that identifies the data
  17547. * @param data the data object to associate to the key for this Engine instance
  17548. * @return true if no such key were already present and the data was added successfully, false otherwise
  17549. */
  17550. Scene.prototype.addExternalData = function (key, data) {
  17551. if (!this._externalData) {
  17552. this._externalData = new BABYLON.StringDictionary();
  17553. }
  17554. return this._externalData.add(key, data);
  17555. };
  17556. /**
  17557. * Get an externaly attached data from its key
  17558. * @param key the unique key that identifies the data
  17559. * @return the associated data, if present (can be null), or undefined if not present
  17560. */
  17561. Scene.prototype.getExternalData = function (key) {
  17562. if (!this._externalData) {
  17563. return null;
  17564. }
  17565. return this._externalData.get(key);
  17566. };
  17567. /**
  17568. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17569. * @param key the unique key that identifies the data
  17570. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17571. * @return the associated data, can be null if the factory returned null.
  17572. */
  17573. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17574. if (!this._externalData) {
  17575. this._externalData = new BABYLON.StringDictionary();
  17576. }
  17577. return this._externalData.getOrAddWithFactory(key, factory);
  17578. };
  17579. /**
  17580. * Remove an externaly attached data from the Engine instance
  17581. * @param key the unique key that identifies the data
  17582. * @return true if the data was successfully removed, false if it doesn't exist
  17583. */
  17584. Scene.prototype.removeExternalData = function (key) {
  17585. return this._externalData.remove(key);
  17586. };
  17587. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17588. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17589. var material = subMesh.getMaterial();
  17590. if (mesh.showSubMeshesBoundingBox) {
  17591. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17592. }
  17593. if (material) {
  17594. // Render targets
  17595. if (material.getRenderTargetTextures) {
  17596. if (this._processedMaterials.indexOf(material) === -1) {
  17597. this._processedMaterials.push(material);
  17598. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17599. }
  17600. }
  17601. // Dispatch
  17602. this._activeIndices.addCount(subMesh.indexCount, false);
  17603. this._renderingManager.dispatch(subMesh);
  17604. }
  17605. }
  17606. };
  17607. Scene.prototype._isInIntermediateRendering = function () {
  17608. return this._intermediateRendering;
  17609. };
  17610. Scene.prototype._evaluateActiveMeshes = function () {
  17611. this.activeCamera._activeMeshes.reset();
  17612. this._activeMeshes.reset();
  17613. this._renderingManager.reset();
  17614. this._processedMaterials.reset();
  17615. this._activeParticleSystems.reset();
  17616. this._activeSkeletons.reset();
  17617. this._softwareSkinnedMeshes.reset();
  17618. if (this._boundingBoxRenderer) {
  17619. this._boundingBoxRenderer.reset();
  17620. }
  17621. // Meshes
  17622. var meshes;
  17623. var len;
  17624. if (this._selectionOctree) {
  17625. var selection = this._selectionOctree.select(this._frustumPlanes);
  17626. meshes = selection.data;
  17627. len = selection.length;
  17628. }
  17629. else {
  17630. len = this.meshes.length;
  17631. meshes = this.meshes;
  17632. }
  17633. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17634. var mesh = meshes[meshIndex];
  17635. if (mesh.isBlocked) {
  17636. continue;
  17637. }
  17638. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17639. if (!mesh.isReady() || !mesh.isEnabled()) {
  17640. continue;
  17641. }
  17642. mesh.computeWorldMatrix();
  17643. // Intersections
  17644. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17645. this._meshesForIntersections.pushNoDuplicate(mesh);
  17646. }
  17647. // Switch to current LOD
  17648. var meshLOD = mesh.getLOD(this.activeCamera);
  17649. if (!meshLOD) {
  17650. continue;
  17651. }
  17652. mesh._preActivate();
  17653. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17654. this._activeMeshes.push(mesh);
  17655. this.activeCamera._activeMeshes.push(mesh);
  17656. mesh._activate(this._renderId);
  17657. this._activeMesh(mesh, meshLOD);
  17658. }
  17659. }
  17660. // Particle systems
  17661. this._particlesDuration.beginMonitoring();
  17662. var beforeParticlesDate = BABYLON.Tools.Now;
  17663. if (this.particlesEnabled) {
  17664. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17665. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17666. var particleSystem = this.particleSystems[particleIndex];
  17667. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  17668. continue;
  17669. }
  17670. var emitter = particleSystem.emitter;
  17671. if (!emitter.position || emitter.isEnabled()) {
  17672. this._activeParticleSystems.push(particleSystem);
  17673. particleSystem.animate();
  17674. this._renderingManager.dispatchParticles(particleSystem);
  17675. }
  17676. }
  17677. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17678. }
  17679. this._particlesDuration.endMonitoring(false);
  17680. };
  17681. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17682. if (mesh.skeleton && this.skeletonsEnabled) {
  17683. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17684. mesh.skeleton.prepare();
  17685. }
  17686. if (!mesh.computeBonesUsingShaders) {
  17687. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17688. }
  17689. }
  17690. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17691. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17692. }
  17693. if (mesh && mesh.subMeshes) {
  17694. // Submeshes Octrees
  17695. var len;
  17696. var subMeshes;
  17697. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17698. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17699. len = intersections.length;
  17700. subMeshes = intersections.data;
  17701. }
  17702. else {
  17703. subMeshes = mesh.subMeshes;
  17704. len = subMeshes.length;
  17705. }
  17706. for (var subIndex = 0; subIndex < len; subIndex++) {
  17707. var subMesh = subMeshes[subIndex];
  17708. this._evaluateSubMesh(subMesh, mesh);
  17709. }
  17710. }
  17711. };
  17712. Scene.prototype.updateTransformMatrix = function (force) {
  17713. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17714. };
  17715. Scene.prototype._renderForCamera = function (camera) {
  17716. var engine = this._engine;
  17717. var startTime = BABYLON.Tools.Now;
  17718. this.activeCamera = camera;
  17719. if (!this.activeCamera)
  17720. throw new Error("Active camera not set");
  17721. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17722. // Viewport
  17723. engine.setViewport(this.activeCamera.viewport);
  17724. // Camera
  17725. this.resetCachedMaterial();
  17726. this._renderId++;
  17727. this.updateTransformMatrix();
  17728. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17729. // Meshes
  17730. this._evaluateActiveMeshesDuration.beginMonitoring();
  17731. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17732. this._evaluateActiveMeshes();
  17733. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17734. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17735. // Software skinning
  17736. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17737. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17738. mesh.applySkeleton(mesh.skeleton);
  17739. }
  17740. // Render targets
  17741. this._renderTargetsDuration.beginMonitoring();
  17742. var needsRestoreFrameBuffer = false;
  17743. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17744. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  17745. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  17746. }
  17747. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17748. this._intermediateRendering = true;
  17749. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17750. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17751. var renderTarget = this._renderTargets.data[renderIndex];
  17752. if (renderTarget._shouldRender()) {
  17753. this._renderId++;
  17754. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17755. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17756. }
  17757. }
  17758. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17759. this._intermediateRendering = false;
  17760. this._renderId++;
  17761. needsRestoreFrameBuffer = true; // Restore back buffer
  17762. }
  17763. // Render HighlightLayer Texture
  17764. var stencilState = this._engine.getStencilBuffer();
  17765. var renderhighlights = false;
  17766. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17767. this._intermediateRendering = true;
  17768. for (var i = 0; i < this.highlightLayers.length; i++) {
  17769. var highlightLayer = this.highlightLayers[i];
  17770. if (highlightLayer.shouldRender() &&
  17771. (!highlightLayer.camera ||
  17772. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17773. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17774. renderhighlights = true;
  17775. var renderTarget = highlightLayer._mainTexture;
  17776. if (renderTarget._shouldRender()) {
  17777. this._renderId++;
  17778. renderTarget.render(false, false);
  17779. needsRestoreFrameBuffer = true;
  17780. }
  17781. }
  17782. }
  17783. this._intermediateRendering = false;
  17784. this._renderId++;
  17785. }
  17786. if (needsRestoreFrameBuffer) {
  17787. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17788. }
  17789. this._renderTargetsDuration.endMonitoring(false);
  17790. // Prepare Frame
  17791. this.postProcessManager._prepareFrame();
  17792. this._renderDuration.beginMonitoring();
  17793. // Backgrounds
  17794. var layerIndex;
  17795. var layer;
  17796. if (this.layers.length) {
  17797. engine.setDepthBuffer(false);
  17798. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17799. layer = this.layers[layerIndex];
  17800. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17801. layer.render();
  17802. }
  17803. }
  17804. engine.setDepthBuffer(true);
  17805. }
  17806. // Render
  17807. BABYLON.Tools.StartPerformanceCounter("Main render");
  17808. // Activate HighlightLayer stencil
  17809. if (renderhighlights) {
  17810. this._engine.setStencilBuffer(true);
  17811. }
  17812. this._renderingManager.render(null, null, true, true);
  17813. // Restore HighlightLayer stencil
  17814. if (renderhighlights) {
  17815. this._engine.setStencilBuffer(stencilState);
  17816. }
  17817. BABYLON.Tools.EndPerformanceCounter("Main render");
  17818. // Bounding boxes
  17819. if (this._boundingBoxRenderer) {
  17820. this._boundingBoxRenderer.render();
  17821. }
  17822. // Lens flares
  17823. if (this.lensFlaresEnabled) {
  17824. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17825. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17826. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17827. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17828. lensFlareSystem.render();
  17829. }
  17830. }
  17831. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17832. }
  17833. // Foregrounds
  17834. if (this.layers.length) {
  17835. engine.setDepthBuffer(false);
  17836. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17837. layer = this.layers[layerIndex];
  17838. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17839. layer.render();
  17840. }
  17841. }
  17842. engine.setDepthBuffer(true);
  17843. }
  17844. // Highlight Layer
  17845. if (renderhighlights) {
  17846. engine.setDepthBuffer(false);
  17847. for (var i = 0; i < this.highlightLayers.length; i++) {
  17848. if (this.highlightLayers[i].shouldRender()) {
  17849. this.highlightLayers[i].render();
  17850. }
  17851. }
  17852. engine.setDepthBuffer(true);
  17853. }
  17854. this._renderDuration.endMonitoring(false);
  17855. // Finalize frame
  17856. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17857. // Update camera
  17858. this.activeCamera._updateFromScene();
  17859. // Reset some special arrays
  17860. this._renderTargets.reset();
  17861. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17862. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17863. };
  17864. Scene.prototype._processSubCameras = function (camera) {
  17865. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17866. this._renderForCamera(camera);
  17867. return;
  17868. }
  17869. // rig cameras
  17870. for (var index = 0; index < camera._rigCameras.length; index++) {
  17871. this._renderForCamera(camera._rigCameras[index]);
  17872. }
  17873. this.activeCamera = camera;
  17874. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17875. // Update camera
  17876. this.activeCamera._updateFromScene();
  17877. };
  17878. Scene.prototype._checkIntersections = function () {
  17879. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17880. var sourceMesh = this._meshesForIntersections.data[index];
  17881. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17882. var action = sourceMesh.actionManager.actions[actionIndex];
  17883. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17884. var parameters = action.getTriggerParameter();
  17885. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17886. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17887. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17888. if (areIntersecting && currentIntersectionInProgress === -1) {
  17889. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17890. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17891. sourceMesh._intersectionsInProgress.push(otherMesh);
  17892. }
  17893. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17894. sourceMesh._intersectionsInProgress.push(otherMesh);
  17895. }
  17896. }
  17897. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17898. //They intersected, and now they don't.
  17899. //is this trigger an exit trigger? execute an event.
  17900. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17901. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17902. }
  17903. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17904. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17905. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17906. }
  17907. }
  17908. }
  17909. }
  17910. }
  17911. };
  17912. Scene.prototype.render = function () {
  17913. if (this.isDisposed) {
  17914. return;
  17915. }
  17916. this._lastFrameDuration.beginMonitoring();
  17917. this._particlesDuration.fetchNewFrame();
  17918. this._spritesDuration.fetchNewFrame();
  17919. this._activeParticles.fetchNewFrame();
  17920. this._renderDuration.fetchNewFrame();
  17921. this._renderTargetsDuration.fetchNewFrame();
  17922. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17923. this._totalVertices.fetchNewFrame();
  17924. this._activeIndices.fetchNewFrame();
  17925. this._activeBones.fetchNewFrame();
  17926. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17927. this._meshesForIntersections.reset();
  17928. this.resetCachedMaterial();
  17929. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17930. // Actions
  17931. if (this.actionManager) {
  17932. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17933. }
  17934. //Simplification Queue
  17935. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17936. this.simplificationQueue.executeNext();
  17937. }
  17938. // Animations
  17939. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17940. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17941. this._animate();
  17942. // Physics
  17943. if (this._physicsEngine) {
  17944. BABYLON.Tools.StartPerformanceCounter("Physics");
  17945. this._physicsEngine._step(deltaTime / 1000.0);
  17946. BABYLON.Tools.EndPerformanceCounter("Physics");
  17947. }
  17948. // Before render
  17949. this.onBeforeRenderObservable.notifyObservers(this);
  17950. // Customs render targets
  17951. this._renderTargetsDuration.beginMonitoring();
  17952. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17953. var engine = this.getEngine();
  17954. var currentActiveCamera = this.activeCamera;
  17955. if (this.renderTargetsEnabled) {
  17956. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17957. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17958. var renderTarget = this.customRenderTargets[customIndex];
  17959. if (renderTarget._shouldRender()) {
  17960. this._renderId++;
  17961. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17962. if (!this.activeCamera)
  17963. throw new Error("Active camera not set");
  17964. // Viewport
  17965. engine.setViewport(this.activeCamera.viewport);
  17966. // Camera
  17967. this.updateTransformMatrix();
  17968. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17969. }
  17970. }
  17971. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17972. this._renderId++;
  17973. }
  17974. // Restore back buffer
  17975. if (this.customRenderTargets.length > 0) {
  17976. engine.restoreDefaultFramebuffer();
  17977. }
  17978. this._renderTargetsDuration.endMonitoring();
  17979. this.activeCamera = currentActiveCamera;
  17980. // Procedural textures
  17981. if (this.proceduralTexturesEnabled) {
  17982. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17983. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17984. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17985. if (proceduralTexture._shouldRender()) {
  17986. proceduralTexture.render();
  17987. }
  17988. }
  17989. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17990. }
  17991. // Clear
  17992. if (this.autoClearDepthAndStencil || this.autoClear) {
  17993. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17994. }
  17995. // Shadows
  17996. if (this.shadowsEnabled) {
  17997. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17998. var light = this.lights[lightIndex];
  17999. var shadowGenerator = light.getShadowGenerator();
  18000. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18001. var shadowMap = shadowGenerator.getShadowMap();
  18002. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18003. this._renderTargets.push(shadowMap);
  18004. }
  18005. }
  18006. }
  18007. }
  18008. // Depth renderer
  18009. if (this._depthRenderer) {
  18010. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18011. }
  18012. // Geometry renderer
  18013. if (this._geometryBufferRenderer) {
  18014. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18015. }
  18016. // RenderPipeline
  18017. if (this._postProcessRenderPipelineManager) {
  18018. this._postProcessRenderPipelineManager.update();
  18019. }
  18020. // Multi-cameras?
  18021. if (this.activeCameras.length > 0) {
  18022. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18023. if (cameraIndex > 0) {
  18024. this._engine.clear(null, false, true, true);
  18025. }
  18026. this._processSubCameras(this.activeCameras[cameraIndex]);
  18027. }
  18028. }
  18029. else {
  18030. if (!this.activeCamera) {
  18031. throw new Error("No camera defined");
  18032. }
  18033. this._processSubCameras(this.activeCamera);
  18034. }
  18035. // Intersection checks
  18036. this._checkIntersections();
  18037. // Update the audio listener attached to the camera
  18038. if (BABYLON.AudioEngine) {
  18039. this._updateAudioParameters();
  18040. }
  18041. // After render
  18042. if (this.afterRender) {
  18043. this.afterRender();
  18044. }
  18045. this.onAfterRenderObservable.notifyObservers(this);
  18046. // Cleaning
  18047. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18048. this._toBeDisposed.data[index].dispose();
  18049. this._toBeDisposed[index] = null;
  18050. }
  18051. this._toBeDisposed.reset();
  18052. if (this.dumpNextRenderTargets) {
  18053. this.dumpNextRenderTargets = false;
  18054. }
  18055. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18056. this._lastFrameDuration.endMonitoring();
  18057. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18058. this._totalLightsCounter.addCount(this.lights.length, true);
  18059. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18060. this._totalTexturesCounter.addCount(this.textures.length, true);
  18061. this._activeBones.addCount(0, true);
  18062. this._activeIndices.addCount(0, true);
  18063. this._activeParticles.addCount(0, true);
  18064. };
  18065. Scene.prototype._updateAudioParameters = function () {
  18066. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18067. return;
  18068. }
  18069. var listeningCamera;
  18070. var audioEngine = BABYLON.Engine.audioEngine;
  18071. if (this.activeCameras.length > 0) {
  18072. listeningCamera = this.activeCameras[0];
  18073. }
  18074. else {
  18075. listeningCamera = this.activeCamera;
  18076. }
  18077. if (listeningCamera && audioEngine.canUseWebAudio) {
  18078. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18079. // for VR cameras
  18080. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18081. listeningCamera = listeningCamera.rigCameras[0];
  18082. }
  18083. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18084. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18085. cameraDirection.normalize();
  18086. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18087. var i;
  18088. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18089. var sound = this.mainSoundTrack.soundCollection[i];
  18090. if (sound.useCustomAttenuation) {
  18091. sound.updateDistanceFromListener();
  18092. }
  18093. }
  18094. for (i = 0; i < this.soundTracks.length; i++) {
  18095. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18096. sound = this.soundTracks[i].soundCollection[j];
  18097. if (sound.useCustomAttenuation) {
  18098. sound.updateDistanceFromListener();
  18099. }
  18100. }
  18101. }
  18102. }
  18103. };
  18104. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18105. // Audio
  18106. get: function () {
  18107. return this._audioEnabled;
  18108. },
  18109. set: function (value) {
  18110. this._audioEnabled = value;
  18111. if (BABYLON.AudioEngine) {
  18112. if (this._audioEnabled) {
  18113. this._enableAudio();
  18114. }
  18115. else {
  18116. this._disableAudio();
  18117. }
  18118. }
  18119. },
  18120. enumerable: true,
  18121. configurable: true
  18122. });
  18123. Scene.prototype._disableAudio = function () {
  18124. var i;
  18125. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18126. this.mainSoundTrack.soundCollection[i].pause();
  18127. }
  18128. for (i = 0; i < this.soundTracks.length; i++) {
  18129. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18130. this.soundTracks[i].soundCollection[j].pause();
  18131. }
  18132. }
  18133. };
  18134. Scene.prototype._enableAudio = function () {
  18135. var i;
  18136. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18137. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18138. this.mainSoundTrack.soundCollection[i].play();
  18139. }
  18140. }
  18141. for (i = 0; i < this.soundTracks.length; i++) {
  18142. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18143. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18144. this.soundTracks[i].soundCollection[j].play();
  18145. }
  18146. }
  18147. }
  18148. };
  18149. Object.defineProperty(Scene.prototype, "headphone", {
  18150. get: function () {
  18151. return this._headphone;
  18152. },
  18153. set: function (value) {
  18154. this._headphone = value;
  18155. if (BABYLON.AudioEngine) {
  18156. if (this._headphone) {
  18157. this._switchAudioModeForHeadphones();
  18158. }
  18159. else {
  18160. this._switchAudioModeForNormalSpeakers();
  18161. }
  18162. }
  18163. },
  18164. enumerable: true,
  18165. configurable: true
  18166. });
  18167. Scene.prototype._switchAudioModeForHeadphones = function () {
  18168. this.mainSoundTrack.switchPanningModelToHRTF();
  18169. for (var i = 0; i < this.soundTracks.length; i++) {
  18170. this.soundTracks[i].switchPanningModelToHRTF();
  18171. }
  18172. };
  18173. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18174. this.mainSoundTrack.switchPanningModelToEqualPower();
  18175. for (var i = 0; i < this.soundTracks.length; i++) {
  18176. this.soundTracks[i].switchPanningModelToEqualPower();
  18177. }
  18178. };
  18179. Scene.prototype.enableDepthRenderer = function () {
  18180. if (this._depthRenderer) {
  18181. return this._depthRenderer;
  18182. }
  18183. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18184. return this._depthRenderer;
  18185. };
  18186. Scene.prototype.disableDepthRenderer = function () {
  18187. if (!this._depthRenderer) {
  18188. return;
  18189. }
  18190. this._depthRenderer.dispose();
  18191. this._depthRenderer = null;
  18192. };
  18193. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18194. if (ratio === void 0) { ratio = 1; }
  18195. if (this._geometryBufferRenderer) {
  18196. return this._geometryBufferRenderer;
  18197. }
  18198. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18199. if (!this._geometryBufferRenderer.isSupported) {
  18200. this._geometryBufferRenderer = null;
  18201. }
  18202. return this._geometryBufferRenderer;
  18203. };
  18204. Scene.prototype.disableGeometryBufferRenderer = function () {
  18205. if (!this._geometryBufferRenderer) {
  18206. return;
  18207. }
  18208. this._geometryBufferRenderer.dispose();
  18209. this._geometryBufferRenderer = null;
  18210. };
  18211. Scene.prototype.freezeMaterials = function () {
  18212. for (var i = 0; i < this.materials.length; i++) {
  18213. this.materials[i].freeze();
  18214. }
  18215. };
  18216. Scene.prototype.unfreezeMaterials = function () {
  18217. for (var i = 0; i < this.materials.length; i++) {
  18218. this.materials[i].unfreeze();
  18219. }
  18220. };
  18221. Scene.prototype.dispose = function () {
  18222. this.beforeRender = null;
  18223. this.afterRender = null;
  18224. this.skeletons = [];
  18225. this.morphTargetManagers = [];
  18226. this.importedMeshesFiles = new Array();
  18227. if (this._depthRenderer) {
  18228. this._depthRenderer.dispose();
  18229. }
  18230. // Smart arrays
  18231. if (this.activeCamera) {
  18232. this.activeCamera._activeMeshes.dispose();
  18233. this.activeCamera = null;
  18234. }
  18235. this._activeMeshes.dispose();
  18236. this._renderingManager.dispose();
  18237. this._processedMaterials.dispose();
  18238. this._activeParticleSystems.dispose();
  18239. this._activeSkeletons.dispose();
  18240. this._softwareSkinnedMeshes.dispose();
  18241. if (this._boundingBoxRenderer) {
  18242. this._boundingBoxRenderer.dispose();
  18243. }
  18244. this._meshesForIntersections.dispose();
  18245. this._toBeDisposed.dispose();
  18246. // Debug layer
  18247. if (this._debugLayer) {
  18248. this._debugLayer.hide();
  18249. }
  18250. // Events
  18251. this.onDisposeObservable.notifyObservers(this);
  18252. this.onDisposeObservable.clear();
  18253. this.onBeforeRenderObservable.clear();
  18254. this.onAfterRenderObservable.clear();
  18255. this.detachControl();
  18256. // Release sounds & sounds tracks
  18257. if (BABYLON.AudioEngine) {
  18258. this.disposeSounds();
  18259. }
  18260. // Detach cameras
  18261. var canvas = this._engine.getRenderingCanvas();
  18262. var index;
  18263. for (index = 0; index < this.cameras.length; index++) {
  18264. this.cameras[index].detachControl(canvas);
  18265. }
  18266. // Release lights
  18267. while (this.lights.length) {
  18268. this.lights[0].dispose();
  18269. }
  18270. // Release meshes
  18271. while (this.meshes.length) {
  18272. this.meshes[0].dispose(true);
  18273. }
  18274. // Release cameras
  18275. while (this.cameras.length) {
  18276. this.cameras[0].dispose();
  18277. }
  18278. // Release materials
  18279. while (this.materials.length) {
  18280. this.materials[0].dispose();
  18281. }
  18282. // Release particles
  18283. while (this.particleSystems.length) {
  18284. this.particleSystems[0].dispose();
  18285. }
  18286. // Release sprites
  18287. while (this.spriteManagers.length) {
  18288. this.spriteManagers[0].dispose();
  18289. }
  18290. // Release layers
  18291. while (this.layers.length) {
  18292. this.layers[0].dispose();
  18293. }
  18294. while (this.highlightLayers.length) {
  18295. this.highlightLayers[0].dispose();
  18296. }
  18297. // Release textures
  18298. while (this.textures.length) {
  18299. this.textures[0].dispose();
  18300. }
  18301. // Release UBO
  18302. this._sceneUbo.dispose();
  18303. // Post-processes
  18304. this.postProcessManager.dispose();
  18305. // Physics
  18306. if (this._physicsEngine) {
  18307. this.disablePhysicsEngine();
  18308. }
  18309. // Remove from engine
  18310. index = this._engine.scenes.indexOf(this);
  18311. if (index > -1) {
  18312. this._engine.scenes.splice(index, 1);
  18313. }
  18314. this._engine.wipeCaches();
  18315. this._engine = null;
  18316. };
  18317. Object.defineProperty(Scene.prototype, "isDisposed", {
  18318. get: function () {
  18319. return !this._engine;
  18320. },
  18321. enumerable: true,
  18322. configurable: true
  18323. });
  18324. // Release sounds & sounds tracks
  18325. Scene.prototype.disposeSounds = function () {
  18326. this.mainSoundTrack.dispose();
  18327. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18328. this.soundTracks[scIndex].dispose();
  18329. }
  18330. };
  18331. // Octrees
  18332. Scene.prototype.getWorldExtends = function () {
  18333. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18334. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18335. for (var index = 0; index < this.meshes.length; index++) {
  18336. var mesh = this.meshes[index];
  18337. mesh.computeWorldMatrix(true);
  18338. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18339. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18340. BABYLON.Tools.CheckExtends(minBox, min, max);
  18341. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18342. }
  18343. return {
  18344. min: min,
  18345. max: max
  18346. };
  18347. };
  18348. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18349. if (maxCapacity === void 0) { maxCapacity = 64; }
  18350. if (maxDepth === void 0) { maxDepth = 2; }
  18351. if (!this._selectionOctree) {
  18352. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18353. }
  18354. var worldExtends = this.getWorldExtends();
  18355. // Update octree
  18356. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18357. return this._selectionOctree;
  18358. };
  18359. // Picking
  18360. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18361. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18362. var engine = this._engine;
  18363. if (!camera) {
  18364. if (!this.activeCamera)
  18365. throw new Error("Active camera not set");
  18366. camera = this.activeCamera;
  18367. }
  18368. var cameraViewport = camera.viewport;
  18369. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18370. // Moving coordinates to local viewport world
  18371. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18372. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18373. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18374. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18375. };
  18376. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18377. if (!BABYLON.PickingInfo) {
  18378. return null;
  18379. }
  18380. var engine = this._engine;
  18381. if (!camera) {
  18382. if (!this.activeCamera)
  18383. throw new Error("Active camera not set");
  18384. camera = this.activeCamera;
  18385. }
  18386. var cameraViewport = camera.viewport;
  18387. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18388. var identity = BABYLON.Matrix.Identity();
  18389. // Moving coordinates to local viewport world
  18390. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18391. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18392. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18393. };
  18394. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18395. if (!BABYLON.PickingInfo) {
  18396. return null;
  18397. }
  18398. var pickingInfo = null;
  18399. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18400. var mesh = this.meshes[meshIndex];
  18401. if (predicate) {
  18402. if (!predicate(mesh)) {
  18403. continue;
  18404. }
  18405. }
  18406. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18407. continue;
  18408. }
  18409. var world = mesh.getWorldMatrix();
  18410. var ray = rayFunction(world);
  18411. var result = mesh.intersects(ray, fastCheck);
  18412. if (!result || !result.hit)
  18413. continue;
  18414. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18415. continue;
  18416. pickingInfo = result;
  18417. if (fastCheck) {
  18418. break;
  18419. }
  18420. }
  18421. return pickingInfo || new BABYLON.PickingInfo();
  18422. };
  18423. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18424. if (!BABYLON.PickingInfo) {
  18425. return null;
  18426. }
  18427. var pickingInfos = new Array();
  18428. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18429. var mesh = this.meshes[meshIndex];
  18430. if (predicate) {
  18431. if (!predicate(mesh)) {
  18432. continue;
  18433. }
  18434. }
  18435. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18436. continue;
  18437. }
  18438. var world = mesh.getWorldMatrix();
  18439. var ray = rayFunction(world);
  18440. var result = mesh.intersects(ray, false);
  18441. if (!result || !result.hit)
  18442. continue;
  18443. pickingInfos.push(result);
  18444. }
  18445. return pickingInfos;
  18446. };
  18447. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18448. if (!BABYLON.PickingInfo) {
  18449. return null;
  18450. }
  18451. var pickingInfo = null;
  18452. camera = camera || this.activeCamera;
  18453. if (this.spriteManagers.length > 0) {
  18454. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18455. var spriteManager = this.spriteManagers[spriteIndex];
  18456. if (!spriteManager.isPickable) {
  18457. continue;
  18458. }
  18459. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18460. if (!result || !result.hit)
  18461. continue;
  18462. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18463. continue;
  18464. pickingInfo = result;
  18465. if (fastCheck) {
  18466. break;
  18467. }
  18468. }
  18469. }
  18470. return pickingInfo || new BABYLON.PickingInfo();
  18471. };
  18472. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18473. /// <param name="x">X position on screen</param>
  18474. /// <param name="y">Y position on screen</param>
  18475. /// <param name="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</param>
  18476. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18477. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18478. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18479. var _this = this;
  18480. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18481. };
  18482. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18483. /// <param name="x">X position on screen</param>
  18484. /// <param name="y">Y position on screen</param>
  18485. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  18486. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18487. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18488. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18489. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18490. };
  18491. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18492. var _this = this;
  18493. return this._internalPick(function (world) {
  18494. if (!_this._pickWithRayInverseMatrix) {
  18495. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18496. }
  18497. world.invertToRef(_this._pickWithRayInverseMatrix);
  18498. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18499. }, predicate, fastCheck);
  18500. };
  18501. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18502. /// <param name="x">X position on screen</param>
  18503. /// <param name="y">Y position on screen</param>
  18504. /// <param name="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</param>
  18505. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18506. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18507. var _this = this;
  18508. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18509. };
  18510. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18511. /// <param name="ray">Ray to use</param>
  18512. /// <param name="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</param>
  18513. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18514. var _this = this;
  18515. return this._internalMultiPick(function (world) {
  18516. if (!_this._pickWithRayInverseMatrix) {
  18517. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18518. }
  18519. world.invertToRef(_this._pickWithRayInverseMatrix);
  18520. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18521. }, predicate);
  18522. };
  18523. Scene.prototype.setPointerOverMesh = function (mesh) {
  18524. if (this._pointerOverMesh === mesh) {
  18525. return;
  18526. }
  18527. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18528. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18529. }
  18530. this._pointerOverMesh = mesh;
  18531. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18532. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18533. }
  18534. };
  18535. Scene.prototype.getPointerOverMesh = function () {
  18536. return this._pointerOverMesh;
  18537. };
  18538. Scene.prototype.setPointerOverSprite = function (sprite) {
  18539. if (this._pointerOverSprite === sprite) {
  18540. return;
  18541. }
  18542. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18543. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18544. }
  18545. this._pointerOverSprite = sprite;
  18546. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18547. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18548. }
  18549. };
  18550. Scene.prototype.getPointerOverSprite = function () {
  18551. return this._pointerOverSprite;
  18552. };
  18553. // Physics
  18554. Scene.prototype.getPhysicsEngine = function () {
  18555. return this._physicsEngine;
  18556. };
  18557. /**
  18558. * Enables physics to the current scene
  18559. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18560. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18561. * @return {boolean} was the physics engine initialized
  18562. */
  18563. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18564. if (this._physicsEngine) {
  18565. return true;
  18566. }
  18567. try {
  18568. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18569. return true;
  18570. }
  18571. catch (e) {
  18572. BABYLON.Tools.Error(e.message);
  18573. return false;
  18574. }
  18575. };
  18576. Scene.prototype.disablePhysicsEngine = function () {
  18577. if (!this._physicsEngine) {
  18578. return;
  18579. }
  18580. this._physicsEngine.dispose();
  18581. this._physicsEngine = undefined;
  18582. };
  18583. Scene.prototype.isPhysicsEnabled = function () {
  18584. return this._physicsEngine !== undefined;
  18585. };
  18586. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18587. var mesh = compound.parts[0].mesh;
  18588. mesh.physicsImpostor.dispose();
  18589. mesh.physicsImpostor = null;
  18590. };
  18591. // Misc.
  18592. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  18593. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18594. if (replace === void 0) { replace = false; }
  18595. if (attachCameraControls === void 0) { attachCameraControls = false; }
  18596. // Dispose existing camera or light in replace mode.
  18597. if (replace) {
  18598. if (this.activeCamera) {
  18599. this.activeCamera.dispose();
  18600. this.activeCamera = null;
  18601. }
  18602. if (this.lights) {
  18603. for (var i = 0; i < this.lights.length; i++) {
  18604. this.lights[i].dispose();
  18605. }
  18606. }
  18607. }
  18608. // Light
  18609. if (this.lights.length === 0) {
  18610. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18611. }
  18612. // Camera
  18613. if (!this.activeCamera) {
  18614. var worldExtends = this.getWorldExtends();
  18615. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18616. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18617. var camera;
  18618. var radius = worldSize.length() * 1.5;
  18619. if (createArcRotateCamera) {
  18620. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  18621. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18622. arcRotateCamera.wheelPrecision = 100 / radius;
  18623. camera = arcRotateCamera;
  18624. }
  18625. else {
  18626. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  18627. freeCamera.setTarget(worldCenter);
  18628. camera = freeCamera;
  18629. }
  18630. camera.minZ = radius * 0.01;
  18631. camera.maxZ = radius * 100;
  18632. camera.speed = radius * 0.2;
  18633. this.activeCamera = camera;
  18634. if (attachCameraControls) {
  18635. camera.attachControl(this.getEngine().getRenderingCanvas());
  18636. }
  18637. }
  18638. };
  18639. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  18640. if (pbr === void 0) { pbr = false; }
  18641. if (scale === void 0) { scale = 1000; }
  18642. if (blur === void 0) { blur = 0; }
  18643. if (environmentTexture) {
  18644. this.environmentTexture = environmentTexture;
  18645. }
  18646. if (!this.environmentTexture) {
  18647. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18648. return;
  18649. }
  18650. // Skybox
  18651. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  18652. if (pbr) {
  18653. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18654. hdrSkyboxMaterial.backFaceCulling = false;
  18655. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  18656. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18657. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  18658. hdrSkyboxMaterial.disableLighting = true;
  18659. hdrSkyboxMaterial.twoSidedLighting = true;
  18660. hdrSkybox.infiniteDistance = true;
  18661. hdrSkybox.material = hdrSkyboxMaterial;
  18662. }
  18663. else {
  18664. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18665. skyboxMaterial.backFaceCulling = false;
  18666. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  18667. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18668. skyboxMaterial.disableLighting = true;
  18669. hdrSkybox.infiniteDistance = true;
  18670. hdrSkybox.material = skyboxMaterial;
  18671. }
  18672. return hdrSkybox;
  18673. };
  18674. // Tags
  18675. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18676. if (tagsQuery === undefined) {
  18677. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18678. return list;
  18679. }
  18680. var listByTags = [];
  18681. forEach = forEach || (function (item) { return; });
  18682. for (var i in list) {
  18683. var item = list[i];
  18684. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18685. listByTags.push(item);
  18686. forEach(item);
  18687. }
  18688. }
  18689. return listByTags;
  18690. };
  18691. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18692. return this._getByTags(this.meshes, tagsQuery, forEach);
  18693. };
  18694. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18695. return this._getByTags(this.cameras, tagsQuery, forEach);
  18696. };
  18697. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18698. return this._getByTags(this.lights, tagsQuery, forEach);
  18699. };
  18700. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18701. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18702. };
  18703. /**
  18704. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18705. * This allowed control for front to back rendering or reversly depending of the special needs.
  18706. *
  18707. * @param renderingGroupId The rendering group id corresponding to its index
  18708. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18709. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18710. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18711. */
  18712. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18713. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18714. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18715. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18716. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18717. };
  18718. /**
  18719. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18720. *
  18721. * @param renderingGroupId The rendering group id corresponding to its index
  18722. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18723. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18724. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18725. */
  18726. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18727. if (depth === void 0) { depth = true; }
  18728. if (stencil === void 0) { stencil = true; }
  18729. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18730. };
  18731. /**
  18732. * Will flag all materials as dirty to trigger new shader compilation
  18733. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18734. */
  18735. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18736. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18737. var material = _a[_i];
  18738. if (predicate && !predicate(material)) {
  18739. continue;
  18740. }
  18741. material.markAsDirty(flag);
  18742. }
  18743. };
  18744. return Scene;
  18745. }());
  18746. // Statics
  18747. Scene._FOGMODE_NONE = 0;
  18748. Scene._FOGMODE_EXP = 1;
  18749. Scene._FOGMODE_EXP2 = 2;
  18750. Scene._FOGMODE_LINEAR = 3;
  18751. Scene.MinDeltaTime = 1.0;
  18752. Scene.MaxDeltaTime = 1000.0;
  18753. Scene.DragMovementThreshold = 10; // in pixels
  18754. Scene.LongPressDelay = 500; // in milliseconds
  18755. Scene.DoubleClickDelay = 300; // in milliseconds
  18756. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18757. BABYLON.Scene = Scene;
  18758. })(BABYLON || (BABYLON = {}));
  18759. //# sourceMappingURL=babylon.scene.js.map
  18760. var BABYLON;
  18761. (function (BABYLON) {
  18762. var Buffer = (function () {
  18763. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18764. if (engine instanceof BABYLON.Mesh) {
  18765. this._engine = engine.getScene().getEngine();
  18766. }
  18767. else {
  18768. this._engine = engine;
  18769. }
  18770. this._updatable = updatable;
  18771. this._data = data;
  18772. this._strideSize = stride;
  18773. if (!postponeInternalCreation) {
  18774. this.create();
  18775. }
  18776. this._instanced = instanced;
  18777. this._instanceDivisor = instanced ? 1 : 0;
  18778. }
  18779. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18780. // a lot of these parameters are ignored as they are overriden by the buffer
  18781. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18782. };
  18783. // Properties
  18784. Buffer.prototype.isUpdatable = function () {
  18785. return this._updatable;
  18786. };
  18787. Buffer.prototype.getData = function () {
  18788. return this._data;
  18789. };
  18790. Buffer.prototype.getBuffer = function () {
  18791. return this._buffer;
  18792. };
  18793. Buffer.prototype.getStrideSize = function () {
  18794. return this._strideSize;
  18795. };
  18796. Buffer.prototype.getIsInstanced = function () {
  18797. return this._instanced;
  18798. };
  18799. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  18800. get: function () {
  18801. return this._instanceDivisor;
  18802. },
  18803. set: function (value) {
  18804. this._instanceDivisor = value;
  18805. if (value == 0) {
  18806. this._instanced = false;
  18807. }
  18808. else {
  18809. this._instanced = true;
  18810. }
  18811. },
  18812. enumerable: true,
  18813. configurable: true
  18814. });
  18815. // Methods
  18816. Buffer.prototype.create = function (data) {
  18817. if (!data && this._buffer) {
  18818. return; // nothing to do
  18819. }
  18820. data = data || this._data;
  18821. if (!this._buffer) {
  18822. if (this._updatable) {
  18823. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18824. this._data = data;
  18825. }
  18826. else {
  18827. this._buffer = this._engine.createVertexBuffer(data);
  18828. }
  18829. }
  18830. else if (this._updatable) {
  18831. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18832. this._data = data;
  18833. }
  18834. };
  18835. Buffer.prototype.update = function (data) {
  18836. this.create(data);
  18837. };
  18838. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18839. if (!this._buffer) {
  18840. return;
  18841. }
  18842. if (this._updatable) {
  18843. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18844. this._data = null;
  18845. }
  18846. };
  18847. Buffer.prototype.dispose = function () {
  18848. if (!this._buffer) {
  18849. return;
  18850. }
  18851. if (this._engine._releaseBuffer(this._buffer)) {
  18852. this._buffer = null;
  18853. }
  18854. };
  18855. return Buffer;
  18856. }());
  18857. BABYLON.Buffer = Buffer;
  18858. })(BABYLON || (BABYLON = {}));
  18859. //# sourceMappingURL=babylon.buffer.js.map
  18860. var BABYLON;
  18861. (function (BABYLON) {
  18862. var VertexBuffer = (function () {
  18863. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18864. if (!stride) {
  18865. // Deduce stride from kind
  18866. switch (kind) {
  18867. case VertexBuffer.PositionKind:
  18868. stride = 3;
  18869. break;
  18870. case VertexBuffer.NormalKind:
  18871. stride = 3;
  18872. break;
  18873. case VertexBuffer.UVKind:
  18874. case VertexBuffer.UV2Kind:
  18875. case VertexBuffer.UV3Kind:
  18876. case VertexBuffer.UV4Kind:
  18877. case VertexBuffer.UV5Kind:
  18878. case VertexBuffer.UV6Kind:
  18879. stride = 2;
  18880. break;
  18881. case VertexBuffer.TangentKind:
  18882. case VertexBuffer.ColorKind:
  18883. stride = 4;
  18884. break;
  18885. case VertexBuffer.MatricesIndicesKind:
  18886. case VertexBuffer.MatricesIndicesExtraKind:
  18887. stride = 4;
  18888. break;
  18889. case VertexBuffer.MatricesWeightsKind:
  18890. case VertexBuffer.MatricesWeightsExtraKind:
  18891. stride = 4;
  18892. break;
  18893. }
  18894. }
  18895. if (data instanceof BABYLON.Buffer) {
  18896. if (!stride) {
  18897. stride = data.getStrideSize();
  18898. }
  18899. this._buffer = data;
  18900. this._ownsBuffer = false;
  18901. }
  18902. else {
  18903. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18904. this._ownsBuffer = true;
  18905. }
  18906. this._stride = stride;
  18907. this._offset = offset ? offset : 0;
  18908. this._size = size ? size : stride;
  18909. this._kind = kind;
  18910. }
  18911. /**
  18912. * Returns the kind of the VertexBuffer (string).
  18913. */
  18914. VertexBuffer.prototype.getKind = function () {
  18915. return this._kind;
  18916. };
  18917. // Properties
  18918. /**
  18919. * Boolean : is the VertexBuffer updatable ?
  18920. */
  18921. VertexBuffer.prototype.isUpdatable = function () {
  18922. return this._buffer.isUpdatable();
  18923. };
  18924. /**
  18925. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18926. */
  18927. VertexBuffer.prototype.getData = function () {
  18928. return this._buffer.getData();
  18929. };
  18930. /**
  18931. * Returns the WebGLBuffer associated to the VertexBuffer.
  18932. */
  18933. VertexBuffer.prototype.getBuffer = function () {
  18934. return this._buffer.getBuffer();
  18935. };
  18936. /**
  18937. * Returns the stride of the VertexBuffer (integer).
  18938. */
  18939. VertexBuffer.prototype.getStrideSize = function () {
  18940. return this._stride;
  18941. };
  18942. /**
  18943. * Returns the offset (integer).
  18944. */
  18945. VertexBuffer.prototype.getOffset = function () {
  18946. return this._offset;
  18947. };
  18948. /**
  18949. * Returns the VertexBuffer total size (integer).
  18950. */
  18951. VertexBuffer.prototype.getSize = function () {
  18952. return this._size;
  18953. };
  18954. /**
  18955. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18956. */
  18957. VertexBuffer.prototype.getIsInstanced = function () {
  18958. return this._buffer.getIsInstanced();
  18959. };
  18960. /**
  18961. * Returns the instancing divisor, zero for non-instanced (integer).
  18962. */
  18963. VertexBuffer.prototype.getInstanceDivisor = function () {
  18964. return this._buffer.instanceDivisor;
  18965. };
  18966. // Methods
  18967. /**
  18968. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18969. * Returns the created WebGLBuffer.
  18970. */
  18971. VertexBuffer.prototype.create = function (data) {
  18972. return this._buffer.create(data);
  18973. };
  18974. /**
  18975. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18976. * Returns the updated WebGLBuffer.
  18977. */
  18978. VertexBuffer.prototype.update = function (data) {
  18979. return this._buffer.update(data);
  18980. };
  18981. /**
  18982. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18983. * Returns the directly updated WebGLBuffer.
  18984. */
  18985. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18986. return this._buffer.updateDirectly(data, offset);
  18987. };
  18988. /**
  18989. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18990. */
  18991. VertexBuffer.prototype.dispose = function () {
  18992. if (this._ownsBuffer) {
  18993. this._buffer.dispose();
  18994. }
  18995. };
  18996. Object.defineProperty(VertexBuffer, "PositionKind", {
  18997. get: function () {
  18998. return VertexBuffer._PositionKind;
  18999. },
  19000. enumerable: true,
  19001. configurable: true
  19002. });
  19003. Object.defineProperty(VertexBuffer, "NormalKind", {
  19004. get: function () {
  19005. return VertexBuffer._NormalKind;
  19006. },
  19007. enumerable: true,
  19008. configurable: true
  19009. });
  19010. Object.defineProperty(VertexBuffer, "TangentKind", {
  19011. get: function () {
  19012. return VertexBuffer._TangentKind;
  19013. },
  19014. enumerable: true,
  19015. configurable: true
  19016. });
  19017. Object.defineProperty(VertexBuffer, "UVKind", {
  19018. get: function () {
  19019. return VertexBuffer._UVKind;
  19020. },
  19021. enumerable: true,
  19022. configurable: true
  19023. });
  19024. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19025. get: function () {
  19026. return VertexBuffer._UV2Kind;
  19027. },
  19028. enumerable: true,
  19029. configurable: true
  19030. });
  19031. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19032. get: function () {
  19033. return VertexBuffer._UV3Kind;
  19034. },
  19035. enumerable: true,
  19036. configurable: true
  19037. });
  19038. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19039. get: function () {
  19040. return VertexBuffer._UV4Kind;
  19041. },
  19042. enumerable: true,
  19043. configurable: true
  19044. });
  19045. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19046. get: function () {
  19047. return VertexBuffer._UV5Kind;
  19048. },
  19049. enumerable: true,
  19050. configurable: true
  19051. });
  19052. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19053. get: function () {
  19054. return VertexBuffer._UV6Kind;
  19055. },
  19056. enumerable: true,
  19057. configurable: true
  19058. });
  19059. Object.defineProperty(VertexBuffer, "ColorKind", {
  19060. get: function () {
  19061. return VertexBuffer._ColorKind;
  19062. },
  19063. enumerable: true,
  19064. configurable: true
  19065. });
  19066. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19067. get: function () {
  19068. return VertexBuffer._MatricesIndicesKind;
  19069. },
  19070. enumerable: true,
  19071. configurable: true
  19072. });
  19073. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19074. get: function () {
  19075. return VertexBuffer._MatricesWeightsKind;
  19076. },
  19077. enumerable: true,
  19078. configurable: true
  19079. });
  19080. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19081. get: function () {
  19082. return VertexBuffer._MatricesIndicesExtraKind;
  19083. },
  19084. enumerable: true,
  19085. configurable: true
  19086. });
  19087. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19088. get: function () {
  19089. return VertexBuffer._MatricesWeightsExtraKind;
  19090. },
  19091. enumerable: true,
  19092. configurable: true
  19093. });
  19094. return VertexBuffer;
  19095. }());
  19096. // Enums
  19097. VertexBuffer._PositionKind = "position";
  19098. VertexBuffer._NormalKind = "normal";
  19099. VertexBuffer._TangentKind = "tangent";
  19100. VertexBuffer._UVKind = "uv";
  19101. VertexBuffer._UV2Kind = "uv2";
  19102. VertexBuffer._UV3Kind = "uv3";
  19103. VertexBuffer._UV4Kind = "uv4";
  19104. VertexBuffer._UV5Kind = "uv5";
  19105. VertexBuffer._UV6Kind = "uv6";
  19106. VertexBuffer._ColorKind = "color";
  19107. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19108. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19109. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19110. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19111. BABYLON.VertexBuffer = VertexBuffer;
  19112. })(BABYLON || (BABYLON = {}));
  19113. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19114. var BABYLON;
  19115. (function (BABYLON) {
  19116. var BaseTexture = (function () {
  19117. function BaseTexture(scene) {
  19118. this._hasAlpha = false;
  19119. this.getAlphaFromRGB = false;
  19120. this.level = 1;
  19121. this.coordinatesIndex = 0;
  19122. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  19123. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  19124. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  19125. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  19126. this.isCube = false;
  19127. this.gammaSpace = true;
  19128. this.invertZ = false;
  19129. this.lodLevelInAlpha = false;
  19130. this.lodGenerationOffset = 0.0;
  19131. this.lodGenerationScale = 0.8;
  19132. this.isRenderTarget = false;
  19133. this.animations = new Array();
  19134. /**
  19135. * An event triggered when the texture is disposed.
  19136. * @type {BABYLON.Observable}
  19137. */
  19138. this.onDisposeObservable = new BABYLON.Observable();
  19139. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19140. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  19141. this._scene.textures.push(this);
  19142. this._uid = null;
  19143. }
  19144. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  19145. get: function () {
  19146. return this._hasAlpha;
  19147. },
  19148. set: function (value) {
  19149. if (this._hasAlpha === value) {
  19150. return;
  19151. }
  19152. this._hasAlpha = value;
  19153. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19154. },
  19155. enumerable: true,
  19156. configurable: true
  19157. });
  19158. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  19159. get: function () {
  19160. return this._coordinatesMode;
  19161. },
  19162. set: function (value) {
  19163. if (this._coordinatesMode === value) {
  19164. return;
  19165. }
  19166. this._coordinatesMode = value;
  19167. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19168. },
  19169. enumerable: true,
  19170. configurable: true
  19171. });
  19172. Object.defineProperty(BaseTexture.prototype, "uid", {
  19173. get: function () {
  19174. if (!this._uid) {
  19175. this._uid = BABYLON.Tools.RandomId();
  19176. }
  19177. return this._uid;
  19178. },
  19179. enumerable: true,
  19180. configurable: true
  19181. });
  19182. BaseTexture.prototype.toString = function () {
  19183. return this.name;
  19184. };
  19185. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  19186. set: function (callback) {
  19187. if (this._onDisposeObserver) {
  19188. this.onDisposeObservable.remove(this._onDisposeObserver);
  19189. }
  19190. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19191. },
  19192. enumerable: true,
  19193. configurable: true
  19194. });
  19195. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  19196. get: function () {
  19197. return true;
  19198. },
  19199. enumerable: true,
  19200. configurable: true
  19201. });
  19202. BaseTexture.prototype.getScene = function () {
  19203. return this._scene;
  19204. };
  19205. BaseTexture.prototype.getTextureMatrix = function () {
  19206. return null;
  19207. };
  19208. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  19209. return null;
  19210. };
  19211. BaseTexture.prototype.getInternalTexture = function () {
  19212. return this._texture;
  19213. };
  19214. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  19215. return !this.isBlocking || this.isReady();
  19216. };
  19217. BaseTexture.prototype.isReady = function () {
  19218. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19219. this.delayLoad();
  19220. return false;
  19221. }
  19222. if (this._texture) {
  19223. return this._texture.isReady;
  19224. }
  19225. return false;
  19226. };
  19227. BaseTexture.prototype.getSize = function () {
  19228. if (this._texture._width) {
  19229. return new BABYLON.Size(this._texture._width, this._texture._height);
  19230. }
  19231. if (this._texture._size) {
  19232. return new BABYLON.Size(this._texture._size, this._texture._size);
  19233. }
  19234. return BABYLON.Size.Zero();
  19235. };
  19236. BaseTexture.prototype.getBaseSize = function () {
  19237. if (!this.isReady() || !this._texture)
  19238. return BABYLON.Size.Zero();
  19239. if (this._texture._size) {
  19240. return new BABYLON.Size(this._texture._size, this._texture._size);
  19241. }
  19242. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19243. };
  19244. BaseTexture.prototype.scale = function (ratio) {
  19245. };
  19246. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19247. get: function () {
  19248. return false;
  19249. },
  19250. enumerable: true,
  19251. configurable: true
  19252. });
  19253. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19254. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19255. for (var index = 0; index < texturesCache.length; index++) {
  19256. var texturesCacheEntry = texturesCache[index];
  19257. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19258. texturesCache.splice(index, 1);
  19259. return;
  19260. }
  19261. }
  19262. };
  19263. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19264. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19265. for (var index = 0; index < texturesCache.length; index++) {
  19266. var texturesCacheEntry = texturesCache[index];
  19267. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19268. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19269. texturesCacheEntry.references++;
  19270. return texturesCacheEntry;
  19271. }
  19272. }
  19273. }
  19274. return null;
  19275. };
  19276. BaseTexture.prototype.delayLoad = function () {
  19277. };
  19278. BaseTexture.prototype.clone = function () {
  19279. return null;
  19280. };
  19281. Object.defineProperty(BaseTexture.prototype, "textureType", {
  19282. get: function () {
  19283. if (!this._texture) {
  19284. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19285. }
  19286. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19287. },
  19288. enumerable: true,
  19289. configurable: true
  19290. });
  19291. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  19292. get: function () {
  19293. if (!this._texture) {
  19294. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19295. }
  19296. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19297. },
  19298. enumerable: true,
  19299. configurable: true
  19300. });
  19301. BaseTexture.prototype.readPixels = function (faceIndex) {
  19302. if (faceIndex === void 0) { faceIndex = 0; }
  19303. if (!this._texture) {
  19304. return null;
  19305. }
  19306. var size = this.getSize();
  19307. var engine = this.getScene().getEngine();
  19308. if (this._texture.isCube) {
  19309. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  19310. }
  19311. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  19312. };
  19313. BaseTexture.prototype.releaseInternalTexture = function () {
  19314. if (this._texture) {
  19315. this._scene.getEngine().releaseInternalTexture(this._texture);
  19316. delete this._texture;
  19317. }
  19318. };
  19319. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  19320. get: function () {
  19321. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  19322. return null;
  19323. }
  19324. if (!this._texture._sphericalPolynomial) {
  19325. this._texture._sphericalPolynomial =
  19326. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  19327. }
  19328. return this._texture._sphericalPolynomial;
  19329. },
  19330. set: function (value) {
  19331. if (this._texture) {
  19332. this._texture._sphericalPolynomial = value;
  19333. }
  19334. },
  19335. enumerable: true,
  19336. configurable: true
  19337. });
  19338. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  19339. get: function () {
  19340. if (this._texture) {
  19341. return this._texture._lodTextureHigh;
  19342. }
  19343. return null;
  19344. },
  19345. enumerable: true,
  19346. configurable: true
  19347. });
  19348. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  19349. get: function () {
  19350. if (this._texture) {
  19351. return this._texture._lodTextureMid;
  19352. }
  19353. return null;
  19354. },
  19355. enumerable: true,
  19356. configurable: true
  19357. });
  19358. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  19359. get: function () {
  19360. if (this._texture) {
  19361. return this._texture._lodTextureLow;
  19362. }
  19363. return null;
  19364. },
  19365. enumerable: true,
  19366. configurable: true
  19367. });
  19368. BaseTexture.prototype.dispose = function () {
  19369. // Animations
  19370. this.getScene().stopAnimation(this);
  19371. // Remove from scene
  19372. this._scene._removePendingData(this);
  19373. var index = this._scene.textures.indexOf(this);
  19374. if (index >= 0) {
  19375. this._scene.textures.splice(index, 1);
  19376. }
  19377. if (this._texture === undefined) {
  19378. return;
  19379. }
  19380. // Release
  19381. this.releaseInternalTexture();
  19382. // Callback
  19383. this.onDisposeObservable.notifyObservers(this);
  19384. this.onDisposeObservable.clear();
  19385. };
  19386. BaseTexture.prototype.serialize = function () {
  19387. if (!this.name) {
  19388. return null;
  19389. }
  19390. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19391. // Animations
  19392. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19393. return serializationObject;
  19394. };
  19395. BaseTexture.WhenAllReady = function (textures, onLoad) {
  19396. var numReady = 0;
  19397. var _loop_1 = function () {
  19398. texture = textures[i];
  19399. if (texture.isReady()) {
  19400. if (++numReady === textures.length) {
  19401. onLoad();
  19402. }
  19403. }
  19404. else {
  19405. observable = texture.onLoadObservable;
  19406. var callback_1 = function () {
  19407. observable.removeCallback(callback_1);
  19408. if (++numReady === textures.length) {
  19409. onLoad();
  19410. }
  19411. };
  19412. observable.add(callback_1);
  19413. }
  19414. };
  19415. var texture, observable;
  19416. for (var i = 0; i < textures.length; i++) {
  19417. _loop_1();
  19418. }
  19419. };
  19420. return BaseTexture;
  19421. }());
  19422. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19423. __decorate([
  19424. BABYLON.serialize()
  19425. ], BaseTexture.prototype, "name", void 0);
  19426. __decorate([
  19427. BABYLON.serialize("hasAlpha")
  19428. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19429. __decorate([
  19430. BABYLON.serialize()
  19431. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19432. __decorate([
  19433. BABYLON.serialize()
  19434. ], BaseTexture.prototype, "level", void 0);
  19435. __decorate([
  19436. BABYLON.serialize()
  19437. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19438. __decorate([
  19439. BABYLON.serialize("coordinatesMode")
  19440. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19441. __decorate([
  19442. BABYLON.serialize()
  19443. ], BaseTexture.prototype, "wrapU", void 0);
  19444. __decorate([
  19445. BABYLON.serialize()
  19446. ], BaseTexture.prototype, "wrapV", void 0);
  19447. __decorate([
  19448. BABYLON.serialize()
  19449. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19450. __decorate([
  19451. BABYLON.serialize()
  19452. ], BaseTexture.prototype, "isCube", void 0);
  19453. __decorate([
  19454. BABYLON.serialize()
  19455. ], BaseTexture.prototype, "gammaSpace", void 0);
  19456. __decorate([
  19457. BABYLON.serialize()
  19458. ], BaseTexture.prototype, "invertZ", void 0);
  19459. __decorate([
  19460. BABYLON.serialize()
  19461. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  19462. __decorate([
  19463. BABYLON.serialize()
  19464. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  19465. __decorate([
  19466. BABYLON.serialize()
  19467. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  19468. __decorate([
  19469. BABYLON.serialize()
  19470. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19471. BABYLON.BaseTexture = BaseTexture;
  19472. })(BABYLON || (BABYLON = {}));
  19473. //# sourceMappingURL=babylon.baseTexture.js.map
  19474. var BABYLON;
  19475. (function (BABYLON) {
  19476. var Texture = (function (_super) {
  19477. __extends(Texture, _super);
  19478. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19479. if (noMipmap === void 0) { noMipmap = false; }
  19480. if (invertY === void 0) { invertY = true; }
  19481. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19482. if (onLoad === void 0) { onLoad = null; }
  19483. if (onError === void 0) { onError = null; }
  19484. if (buffer === void 0) { buffer = null; }
  19485. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19486. var _this = _super.call(this, scene) || this;
  19487. _this.uOffset = 0;
  19488. _this.vOffset = 0;
  19489. _this.uScale = 1.0;
  19490. _this.vScale = 1.0;
  19491. _this.uAng = 0;
  19492. _this.vAng = 0;
  19493. _this.wAng = 0;
  19494. _this._isBlocking = true;
  19495. _this.name = url;
  19496. _this.url = url;
  19497. _this._noMipmap = noMipmap;
  19498. _this._invertY = invertY;
  19499. _this._samplingMode = samplingMode;
  19500. _this._buffer = buffer;
  19501. _this._deleteBuffer = deleteBuffer;
  19502. _this._format = format;
  19503. scene = _this.getScene();
  19504. var load = function () {
  19505. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19506. _this.onLoadObservable.notifyObservers(_this);
  19507. }
  19508. if (onLoad) {
  19509. onLoad();
  19510. }
  19511. if (!_this.isBlocking) {
  19512. scene.resetCachedMaterial();
  19513. }
  19514. };
  19515. if (!url) {
  19516. _this._delayedOnLoad = load;
  19517. _this._delayedOnError = onError;
  19518. return _this;
  19519. }
  19520. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19521. if (!_this._texture) {
  19522. if (!scene.useDelayedTextureLoading) {
  19523. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19524. if (deleteBuffer) {
  19525. delete _this._buffer;
  19526. }
  19527. }
  19528. else {
  19529. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19530. _this._delayedOnLoad = load;
  19531. _this._delayedOnError = onError;
  19532. }
  19533. }
  19534. else {
  19535. if (_this._texture.isReady) {
  19536. BABYLON.Tools.SetImmediate(function () { return load(); });
  19537. }
  19538. else {
  19539. _this._texture.onLoadedCallbacks.push(load);
  19540. }
  19541. }
  19542. return _this;
  19543. }
  19544. Object.defineProperty(Texture.prototype, "noMipmap", {
  19545. get: function () {
  19546. return this._noMipmap;
  19547. },
  19548. enumerable: true,
  19549. configurable: true
  19550. });
  19551. Object.defineProperty(Texture.prototype, "isBlocking", {
  19552. get: function () {
  19553. return this._isBlocking;
  19554. },
  19555. set: function (value) {
  19556. this._isBlocking = value;
  19557. },
  19558. enumerable: true,
  19559. configurable: true
  19560. });
  19561. Object.defineProperty(Texture.prototype, "samplingMode", {
  19562. get: function () {
  19563. return this._samplingMode;
  19564. },
  19565. enumerable: true,
  19566. configurable: true
  19567. });
  19568. Texture.prototype.updateURL = function (url) {
  19569. this.url = url;
  19570. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19571. this.delayLoad();
  19572. };
  19573. Texture.prototype.delayLoad = function () {
  19574. var _this = this;
  19575. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19576. return;
  19577. }
  19578. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19579. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19580. if (!this._texture) {
  19581. 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);
  19582. if (this._deleteBuffer) {
  19583. delete this._buffer;
  19584. }
  19585. }
  19586. else {
  19587. if (this._texture.isReady) {
  19588. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19589. }
  19590. else {
  19591. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19592. }
  19593. }
  19594. };
  19595. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19596. if (!this._texture) {
  19597. return;
  19598. }
  19599. this._samplingMode = samplingMode;
  19600. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19601. };
  19602. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19603. x *= this.uScale;
  19604. y *= this.vScale;
  19605. x -= 0.5 * this.uScale;
  19606. y -= 0.5 * this.vScale;
  19607. z -= 0.5;
  19608. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19609. t.x += 0.5 * this.uScale + this.uOffset;
  19610. t.y += 0.5 * this.vScale + this.vOffset;
  19611. t.z += 0.5;
  19612. };
  19613. Texture.prototype.getTextureMatrix = function () {
  19614. var _this = this;
  19615. if (this.uOffset === this._cachedUOffset &&
  19616. this.vOffset === this._cachedVOffset &&
  19617. this.uScale === this._cachedUScale &&
  19618. this.vScale === this._cachedVScale &&
  19619. this.uAng === this._cachedUAng &&
  19620. this.vAng === this._cachedVAng &&
  19621. this.wAng === this._cachedWAng) {
  19622. return this._cachedTextureMatrix;
  19623. }
  19624. this._cachedUOffset = this.uOffset;
  19625. this._cachedVOffset = this.vOffset;
  19626. this._cachedUScale = this.uScale;
  19627. this._cachedVScale = this.vScale;
  19628. this._cachedUAng = this.uAng;
  19629. this._cachedVAng = this.vAng;
  19630. this._cachedWAng = this.wAng;
  19631. if (!this._cachedTextureMatrix) {
  19632. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19633. this._rowGenerationMatrix = new BABYLON.Matrix();
  19634. this._t0 = BABYLON.Vector3.Zero();
  19635. this._t1 = BABYLON.Vector3.Zero();
  19636. this._t2 = BABYLON.Vector3.Zero();
  19637. }
  19638. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19639. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19640. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19641. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19642. this._t1.subtractInPlace(this._t0);
  19643. this._t2.subtractInPlace(this._t0);
  19644. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19645. this._cachedTextureMatrix.m[0] = this._t1.x;
  19646. this._cachedTextureMatrix.m[1] = this._t1.y;
  19647. this._cachedTextureMatrix.m[2] = this._t1.z;
  19648. this._cachedTextureMatrix.m[4] = this._t2.x;
  19649. this._cachedTextureMatrix.m[5] = this._t2.y;
  19650. this._cachedTextureMatrix.m[6] = this._t2.z;
  19651. this._cachedTextureMatrix.m[8] = this._t0.x;
  19652. this._cachedTextureMatrix.m[9] = this._t0.y;
  19653. this._cachedTextureMatrix.m[10] = this._t0.z;
  19654. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  19655. return mat.hasTexture(_this);
  19656. });
  19657. return this._cachedTextureMatrix;
  19658. };
  19659. Texture.prototype.getReflectionTextureMatrix = function () {
  19660. var _this = this;
  19661. if (this.uOffset === this._cachedUOffset &&
  19662. this.vOffset === this._cachedVOffset &&
  19663. this.uScale === this._cachedUScale &&
  19664. this.vScale === this._cachedVScale &&
  19665. this.coordinatesMode === this._cachedCoordinatesMode) {
  19666. return this._cachedTextureMatrix;
  19667. }
  19668. if (!this._cachedTextureMatrix) {
  19669. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19670. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19671. }
  19672. this._cachedUOffset = this.uOffset;
  19673. this._cachedVOffset = this.vOffset;
  19674. this._cachedUScale = this.uScale;
  19675. this._cachedVScale = this.vScale;
  19676. this._cachedCoordinatesMode = this.coordinatesMode;
  19677. switch (this.coordinatesMode) {
  19678. case Texture.PLANAR_MODE:
  19679. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19680. this._cachedTextureMatrix[0] = this.uScale;
  19681. this._cachedTextureMatrix[5] = this.vScale;
  19682. this._cachedTextureMatrix[12] = this.uOffset;
  19683. this._cachedTextureMatrix[13] = this.vOffset;
  19684. break;
  19685. case Texture.PROJECTION_MODE:
  19686. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19687. this._projectionModeMatrix.m[0] = 0.5;
  19688. this._projectionModeMatrix.m[5] = -0.5;
  19689. this._projectionModeMatrix.m[10] = 0.0;
  19690. this._projectionModeMatrix.m[12] = 0.5;
  19691. this._projectionModeMatrix.m[13] = 0.5;
  19692. this._projectionModeMatrix.m[14] = 1.0;
  19693. this._projectionModeMatrix.m[15] = 1.0;
  19694. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19695. break;
  19696. default:
  19697. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19698. break;
  19699. }
  19700. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  19701. return (mat.getActiveTextures().indexOf(_this) !== -1);
  19702. });
  19703. return this._cachedTextureMatrix;
  19704. };
  19705. Texture.prototype.clone = function () {
  19706. var _this = this;
  19707. return BABYLON.SerializationHelper.Clone(function () {
  19708. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19709. }, this);
  19710. };
  19711. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19712. get: function () {
  19713. if (!this._onLoadObservable) {
  19714. this._onLoadObservable = new BABYLON.Observable();
  19715. }
  19716. return this._onLoadObservable;
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Texture.prototype.serialize = function () {
  19722. var serializationObject = _super.prototype.serialize.call(this);
  19723. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  19724. serializationObject.base64String = this._buffer;
  19725. serializationObject.name = serializationObject.name.replace("data:", "");
  19726. }
  19727. return serializationObject;
  19728. };
  19729. // Statics
  19730. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19731. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19732. if (onLoad === void 0) { onLoad = null; }
  19733. if (onError === void 0) { onError = null; }
  19734. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19735. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19736. };
  19737. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19738. if (parsedTexture.customType) {
  19739. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19740. // Update Sampling Mode
  19741. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19742. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19743. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19744. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19745. }
  19746. }
  19747. return parsedCustomTexture;
  19748. }
  19749. if (parsedTexture.isCube) {
  19750. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19751. }
  19752. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19753. return null;
  19754. }
  19755. var texture = BABYLON.SerializationHelper.Parse(function () {
  19756. if (parsedTexture.mirrorPlane) {
  19757. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19758. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19759. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19760. return mirrorTexture;
  19761. }
  19762. else if (parsedTexture.isRenderTarget) {
  19763. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19764. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19765. return renderTargetTexture;
  19766. }
  19767. else {
  19768. var texture;
  19769. if (parsedTexture.base64String) {
  19770. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19771. }
  19772. else {
  19773. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19774. }
  19775. return texture;
  19776. }
  19777. }, parsedTexture, scene);
  19778. // Update Sampling Mode
  19779. if (parsedTexture.samplingMode) {
  19780. var sampling = parsedTexture.samplingMode;
  19781. if (texture._samplingMode !== sampling) {
  19782. texture.updateSamplingMode(sampling);
  19783. }
  19784. }
  19785. // Animations
  19786. if (parsedTexture.animations) {
  19787. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19788. var parsedAnimation = parsedTexture.animations[animationIndex];
  19789. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19790. }
  19791. }
  19792. return texture;
  19793. };
  19794. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19795. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19796. if (noMipmap === void 0) { noMipmap = false; }
  19797. if (invertY === void 0) { invertY = true; }
  19798. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19799. if (onLoad === void 0) { onLoad = null; }
  19800. if (onError === void 0) { onError = null; }
  19801. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19802. if (name.substr(0, 5) !== "data:") {
  19803. name = "data:" + name;
  19804. }
  19805. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19806. };
  19807. return Texture;
  19808. }(BABYLON.BaseTexture));
  19809. // Constants
  19810. Texture.NEAREST_SAMPLINGMODE = 1;
  19811. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  19812. Texture.BILINEAR_SAMPLINGMODE = 2;
  19813. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  19814. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19815. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  19816. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  19817. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  19818. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  19819. Texture.NEAREST_LINEAR = 7;
  19820. Texture.NEAREST_NEAREST = 8;
  19821. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  19822. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  19823. Texture.LINEAR_LINEAR = 11;
  19824. Texture.LINEAR_NEAREST = 12;
  19825. Texture.EXPLICIT_MODE = 0;
  19826. Texture.SPHERICAL_MODE = 1;
  19827. Texture.PLANAR_MODE = 2;
  19828. Texture.CUBIC_MODE = 3;
  19829. Texture.PROJECTION_MODE = 4;
  19830. Texture.SKYBOX_MODE = 5;
  19831. Texture.INVCUBIC_MODE = 6;
  19832. Texture.EQUIRECTANGULAR_MODE = 7;
  19833. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19834. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19835. Texture.CLAMP_ADDRESSMODE = 0;
  19836. Texture.WRAP_ADDRESSMODE = 1;
  19837. Texture.MIRROR_ADDRESSMODE = 2;
  19838. __decorate([
  19839. BABYLON.serialize()
  19840. ], Texture.prototype, "url", void 0);
  19841. __decorate([
  19842. BABYLON.serialize()
  19843. ], Texture.prototype, "uOffset", void 0);
  19844. __decorate([
  19845. BABYLON.serialize()
  19846. ], Texture.prototype, "vOffset", void 0);
  19847. __decorate([
  19848. BABYLON.serialize()
  19849. ], Texture.prototype, "uScale", void 0);
  19850. __decorate([
  19851. BABYLON.serialize()
  19852. ], Texture.prototype, "vScale", void 0);
  19853. __decorate([
  19854. BABYLON.serialize()
  19855. ], Texture.prototype, "uAng", void 0);
  19856. __decorate([
  19857. BABYLON.serialize()
  19858. ], Texture.prototype, "vAng", void 0);
  19859. __decorate([
  19860. BABYLON.serialize()
  19861. ], Texture.prototype, "wAng", void 0);
  19862. __decorate([
  19863. BABYLON.serialize()
  19864. ], Texture.prototype, "isBlocking", null);
  19865. BABYLON.Texture = Texture;
  19866. })(BABYLON || (BABYLON = {}));
  19867. //# sourceMappingURL=babylon.texture.js.map
  19868. var BABYLON;
  19869. (function (BABYLON) {
  19870. var _InstancesBatch = (function () {
  19871. function _InstancesBatch() {
  19872. this.mustReturn = false;
  19873. this.visibleInstances = new Array();
  19874. this.renderSelf = new Array();
  19875. }
  19876. return _InstancesBatch;
  19877. }());
  19878. BABYLON._InstancesBatch = _InstancesBatch;
  19879. var Mesh = (function (_super) {
  19880. __extends(Mesh, _super);
  19881. /**
  19882. * @constructor
  19883. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19884. * @param {Scene} scene The scene to add this mesh to.
  19885. * @param {Node} parent The parent of this mesh, if it has one
  19886. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19887. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19888. * When false, achieved by calling a clone(), also passing False.
  19889. * This will make creation of children, recursive.
  19890. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19891. */
  19892. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19893. if (parent === void 0) { parent = null; }
  19894. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19895. var _this = _super.call(this, name, scene) || this;
  19896. // Events
  19897. /**
  19898. * An event triggered before rendering the mesh
  19899. * @type {BABYLON.Observable}
  19900. */
  19901. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19902. /**
  19903. * An event triggered after rendering the mesh
  19904. * @type {BABYLON.Observable}
  19905. */
  19906. _this.onAfterRenderObservable = new BABYLON.Observable();
  19907. /**
  19908. * An event triggered before drawing the mesh
  19909. * @type {BABYLON.Observable}
  19910. */
  19911. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19912. // Members
  19913. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19914. _this.instances = new Array();
  19915. _this._LODLevels = new Array();
  19916. _this._visibleInstances = {};
  19917. _this._renderIdForInstances = new Array();
  19918. _this._batchCache = new _InstancesBatch();
  19919. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19920. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19921. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19922. // Will be used to save a source mesh reference, If any
  19923. _this._source = null;
  19924. if (source) {
  19925. // Source mesh
  19926. _this._source = source;
  19927. // Geometry
  19928. if (source._geometry) {
  19929. source._geometry.applyToMesh(_this);
  19930. }
  19931. // Deep copy
  19932. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19933. // Parent
  19934. _this.parent = source.parent;
  19935. // Pivot
  19936. _this.setPivotMatrix(source.getPivotMatrix());
  19937. _this.id = name + "." + source.id;
  19938. // Material
  19939. _this.material = source.material;
  19940. var index;
  19941. if (!doNotCloneChildren) {
  19942. // Children
  19943. for (index = 0; index < scene.meshes.length; index++) {
  19944. var mesh = scene.meshes[index];
  19945. if (mesh.parent === source) {
  19946. // doNotCloneChildren is always going to be False
  19947. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19948. }
  19949. }
  19950. }
  19951. // Physics clone
  19952. var physicsEngine = _this.getScene().getPhysicsEngine();
  19953. if (clonePhysicsImpostor && physicsEngine) {
  19954. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19955. if (impostor) {
  19956. _this.physicsImpostor = impostor.clone(_this);
  19957. }
  19958. }
  19959. // Particles
  19960. for (index = 0; index < scene.particleSystems.length; index++) {
  19961. var system = scene.particleSystems[index];
  19962. if (system.emitter === source) {
  19963. system.clone(system.name, _this);
  19964. }
  19965. }
  19966. _this.computeWorldMatrix(true);
  19967. }
  19968. // Parent
  19969. if (parent !== null) {
  19970. _this.parent = parent;
  19971. }
  19972. return _this;
  19973. }
  19974. Object.defineProperty(Mesh, "FRONTSIDE", {
  19975. /**
  19976. * Mesh side orientation : usually the external or front surface
  19977. */
  19978. get: function () {
  19979. return Mesh._FRONTSIDE;
  19980. },
  19981. enumerable: true,
  19982. configurable: true
  19983. });
  19984. Object.defineProperty(Mesh, "BACKSIDE", {
  19985. /**
  19986. * Mesh side orientation : usually the internal or back surface
  19987. */
  19988. get: function () {
  19989. return Mesh._BACKSIDE;
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19995. /**
  19996. * Mesh side orientation : both internal and external or front and back surfaces
  19997. */
  19998. get: function () {
  19999. return Mesh._DOUBLESIDE;
  20000. },
  20001. enumerable: true,
  20002. configurable: true
  20003. });
  20004. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20005. /**
  20006. * Mesh side orientation : by default, `FRONTSIDE`
  20007. */
  20008. get: function () {
  20009. return Mesh._DEFAULTSIDE;
  20010. },
  20011. enumerable: true,
  20012. configurable: true
  20013. });
  20014. Object.defineProperty(Mesh, "NO_CAP", {
  20015. /**
  20016. * Mesh cap setting : no cap
  20017. */
  20018. get: function () {
  20019. return Mesh._NO_CAP;
  20020. },
  20021. enumerable: true,
  20022. configurable: true
  20023. });
  20024. Object.defineProperty(Mesh, "CAP_START", {
  20025. /**
  20026. * Mesh cap setting : one cap at the beginning of the mesh
  20027. */
  20028. get: function () {
  20029. return Mesh._CAP_START;
  20030. },
  20031. enumerable: true,
  20032. configurable: true
  20033. });
  20034. Object.defineProperty(Mesh, "CAP_END", {
  20035. /**
  20036. * Mesh cap setting : one cap at the end of the mesh
  20037. */
  20038. get: function () {
  20039. return Mesh._CAP_END;
  20040. },
  20041. enumerable: true,
  20042. configurable: true
  20043. });
  20044. Object.defineProperty(Mesh, "CAP_ALL", {
  20045. /**
  20046. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20047. */
  20048. get: function () {
  20049. return Mesh._CAP_ALL;
  20050. },
  20051. enumerable: true,
  20052. configurable: true
  20053. });
  20054. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20055. set: function (callback) {
  20056. if (this._onBeforeDrawObserver) {
  20057. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20058. }
  20059. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20060. },
  20061. enumerable: true,
  20062. configurable: true
  20063. });
  20064. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  20065. get: function () {
  20066. return this._morphTargetManager;
  20067. },
  20068. set: function (value) {
  20069. if (this._morphTargetManager === value) {
  20070. return;
  20071. }
  20072. this._morphTargetManager = value;
  20073. this._syncGeometryWithMorphTargetManager();
  20074. },
  20075. enumerable: true,
  20076. configurable: true
  20077. });
  20078. Object.defineProperty(Mesh.prototype, "source", {
  20079. get: function () {
  20080. return this._source;
  20081. },
  20082. enumerable: true,
  20083. configurable: true
  20084. });
  20085. // Methods
  20086. /**
  20087. * Returns the string "Mesh".
  20088. */
  20089. Mesh.prototype.getClassName = function () {
  20090. return "Mesh";
  20091. };
  20092. /**
  20093. * Returns a string.
  20094. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20095. */
  20096. Mesh.prototype.toString = function (fullDetails) {
  20097. var ret = _super.prototype.toString.call(this, fullDetails);
  20098. ret += ", n vertices: " + this.getTotalVertices();
  20099. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20100. if (this.animations) {
  20101. for (var i = 0; i < this.animations.length; i++) {
  20102. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20103. }
  20104. }
  20105. if (fullDetails) {
  20106. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20107. }
  20108. return ret;
  20109. };
  20110. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20111. /**
  20112. * True if the mesh has some Levels Of Details (LOD).
  20113. * Returns a boolean.
  20114. */
  20115. get: function () {
  20116. return this._LODLevels.length > 0;
  20117. },
  20118. enumerable: true,
  20119. configurable: true
  20120. });
  20121. Mesh.prototype._sortLODLevels = function () {
  20122. this._LODLevels.sort(function (a, b) {
  20123. if (a.distance < b.distance) {
  20124. return 1;
  20125. }
  20126. if (a.distance > b.distance) {
  20127. return -1;
  20128. }
  20129. return 0;
  20130. });
  20131. };
  20132. /**
  20133. * Add a mesh as LOD level triggered at the given distance.
  20134. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20135. * @param {number} distance The distance from the center of the object to show this level
  20136. * @param {Mesh} mesh The mesh to be added as LOD level
  20137. * @return {Mesh} This mesh (for chaining)
  20138. */
  20139. Mesh.prototype.addLODLevel = function (distance, mesh) {
  20140. if (mesh && mesh._masterMesh) {
  20141. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  20142. return this;
  20143. }
  20144. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  20145. this._LODLevels.push(level);
  20146. if (mesh) {
  20147. mesh._masterMesh = this;
  20148. }
  20149. this._sortLODLevels();
  20150. return this;
  20151. };
  20152. /**
  20153. * Returns the LOD level mesh at the passed distance or null if not found.
  20154. * It is related to the method `addLODLevel(distance, mesh)`.
  20155. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20156. * Returns an object Mesh or `null`.
  20157. */
  20158. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  20159. for (var index = 0; index < this._LODLevels.length; index++) {
  20160. var level = this._LODLevels[index];
  20161. if (level.distance === distance) {
  20162. return level.mesh;
  20163. }
  20164. }
  20165. return null;
  20166. };
  20167. /**
  20168. * Remove a mesh from the LOD array
  20169. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20170. * @param {Mesh} mesh The mesh to be removed.
  20171. * @return {Mesh} This mesh (for chaining)
  20172. */
  20173. Mesh.prototype.removeLODLevel = function (mesh) {
  20174. for (var index = 0; index < this._LODLevels.length; index++) {
  20175. if (this._LODLevels[index].mesh === mesh) {
  20176. this._LODLevels.splice(index, 1);
  20177. if (mesh) {
  20178. mesh._masterMesh = null;
  20179. }
  20180. }
  20181. }
  20182. this._sortLODLevels();
  20183. return this;
  20184. };
  20185. /**
  20186. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  20187. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20188. */
  20189. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  20190. if (!this._LODLevels || this._LODLevels.length === 0) {
  20191. return this;
  20192. }
  20193. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20194. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20195. if (this.onLODLevelSelection) {
  20196. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20197. }
  20198. return this;
  20199. }
  20200. for (var index = 0; index < this._LODLevels.length; index++) {
  20201. var level = this._LODLevels[index];
  20202. if (level.distance < distanceToCamera) {
  20203. if (level.mesh) {
  20204. level.mesh._preActivate();
  20205. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20206. }
  20207. if (this.onLODLevelSelection) {
  20208. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20209. }
  20210. return level.mesh;
  20211. }
  20212. }
  20213. if (this.onLODLevelSelection) {
  20214. this.onLODLevelSelection(distanceToCamera, this, this);
  20215. }
  20216. return this;
  20217. };
  20218. Object.defineProperty(Mesh.prototype, "geometry", {
  20219. /**
  20220. * Returns the mesh internal Geometry object.
  20221. */
  20222. get: function () {
  20223. return this._geometry;
  20224. },
  20225. enumerable: true,
  20226. configurable: true
  20227. });
  20228. /**
  20229. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20230. */
  20231. Mesh.prototype.getTotalVertices = function () {
  20232. if (!this._geometry) {
  20233. return 0;
  20234. }
  20235. return this._geometry.getTotalVertices();
  20236. };
  20237. /**
  20238. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20239. * 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.
  20240. * You can force the copy with forceCopy === true
  20241. * Returns null if the mesh has no geometry or no vertex buffer.
  20242. * Possible `kind` values :
  20243. * - BABYLON.VertexBuffer.PositionKind
  20244. * - BABYLON.VertexBuffer.UVKind
  20245. * - BABYLON.VertexBuffer.UV2Kind
  20246. * - BABYLON.VertexBuffer.UV3Kind
  20247. * - BABYLON.VertexBuffer.UV4Kind
  20248. * - BABYLON.VertexBuffer.UV5Kind
  20249. * - BABYLON.VertexBuffer.UV6Kind
  20250. * - BABYLON.VertexBuffer.ColorKind
  20251. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20252. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20253. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20254. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20255. */
  20256. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  20257. if (!this._geometry) {
  20258. return null;
  20259. }
  20260. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  20261. };
  20262. /**
  20263. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20264. * Returns `undefined` if the mesh has no geometry.
  20265. * Possible `kind` values :
  20266. * - BABYLON.VertexBuffer.PositionKind
  20267. * - BABYLON.VertexBuffer.UVKind
  20268. * - BABYLON.VertexBuffer.UV2Kind
  20269. * - BABYLON.VertexBuffer.UV3Kind
  20270. * - BABYLON.VertexBuffer.UV4Kind
  20271. * - BABYLON.VertexBuffer.UV5Kind
  20272. * - BABYLON.VertexBuffer.UV6Kind
  20273. * - BABYLON.VertexBuffer.ColorKind
  20274. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20275. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20276. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20277. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20278. */
  20279. Mesh.prototype.getVertexBuffer = function (kind) {
  20280. if (!this._geometry) {
  20281. return undefined;
  20282. }
  20283. return this._geometry.getVertexBuffer(kind);
  20284. };
  20285. /**
  20286. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20287. * Possible `kind` values :
  20288. * - BABYLON.VertexBuffer.PositionKind
  20289. * - BABYLON.VertexBuffer.UVKind
  20290. * - BABYLON.VertexBuffer.UV2Kind
  20291. * - BABYLON.VertexBuffer.UV3Kind
  20292. * - BABYLON.VertexBuffer.UV4Kind
  20293. * - BABYLON.VertexBuffer.UV5Kind
  20294. * - BABYLON.VertexBuffer.UV6Kind
  20295. * - BABYLON.VertexBuffer.ColorKind
  20296. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20297. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20298. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20299. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20300. */
  20301. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20302. if (!this._geometry) {
  20303. if (this._delayInfo) {
  20304. return this._delayInfo.indexOf(kind) !== -1;
  20305. }
  20306. return false;
  20307. }
  20308. return this._geometry.isVerticesDataPresent(kind);
  20309. };
  20310. /**
  20311. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20312. * Possible `kind` values :
  20313. * - BABYLON.VertexBuffer.PositionKind
  20314. * - BABYLON.VertexBuffer.UVKind
  20315. * - BABYLON.VertexBuffer.UV2Kind
  20316. * - BABYLON.VertexBuffer.UV3Kind
  20317. * - BABYLON.VertexBuffer.UV4Kind
  20318. * - BABYLON.VertexBuffer.UV5Kind
  20319. * - BABYLON.VertexBuffer.UV6Kind
  20320. * - BABYLON.VertexBuffer.ColorKind
  20321. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20322. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20323. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20324. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20325. */
  20326. Mesh.prototype.getVerticesDataKinds = function () {
  20327. if (!this._geometry) {
  20328. var result = [];
  20329. if (this._delayInfo) {
  20330. this._delayInfo.forEach(function (kind, index, array) {
  20331. result.push(kind);
  20332. });
  20333. }
  20334. return result;
  20335. }
  20336. return this._geometry.getVerticesDataKinds();
  20337. };
  20338. /**
  20339. * Returns a positive integer : the total number of indices in this mesh geometry.
  20340. * Returns zero if the mesh has no geometry.
  20341. */
  20342. Mesh.prototype.getTotalIndices = function () {
  20343. if (!this._geometry) {
  20344. return 0;
  20345. }
  20346. return this._geometry.getTotalIndices();
  20347. };
  20348. /**
  20349. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20350. * 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.
  20351. * Returns an empty array if the mesh has no geometry.
  20352. */
  20353. Mesh.prototype.getIndices = function (copyWhenShared) {
  20354. if (!this._geometry) {
  20355. return [];
  20356. }
  20357. return this._geometry.getIndices(copyWhenShared);
  20358. };
  20359. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20360. get: function () {
  20361. return this._masterMesh !== null && this._masterMesh !== undefined;
  20362. },
  20363. enumerable: true,
  20364. configurable: true
  20365. });
  20366. /**
  20367. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20368. */
  20369. Mesh.prototype.isReady = function () {
  20370. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20371. return false;
  20372. }
  20373. return _super.prototype.isReady.call(this);
  20374. };
  20375. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20376. get: function () {
  20377. return this._sideOrientation;
  20378. },
  20379. /**
  20380. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20381. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20382. */
  20383. set: function (sideO) {
  20384. this._sideOrientation = sideO;
  20385. },
  20386. enumerable: true,
  20387. configurable: true
  20388. });
  20389. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20390. /**
  20391. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20392. * This property is pertinent only for updatable parametric shapes.
  20393. */
  20394. get: function () {
  20395. return this._areNormalsFrozen;
  20396. },
  20397. enumerable: true,
  20398. configurable: true
  20399. });
  20400. /**
  20401. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20402. * It has no effect at all on other shapes.
  20403. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20404. * Returns the Mesh.
  20405. */
  20406. Mesh.prototype.freezeNormals = function () {
  20407. this._areNormalsFrozen = true;
  20408. return this;
  20409. };
  20410. /**
  20411. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20412. * It has no effect at all on other shapes.
  20413. * It reactivates the mesh normals computation if it was previously frozen.
  20414. * Returns the Mesh.
  20415. */
  20416. Mesh.prototype.unfreezeNormals = function () {
  20417. this._areNormalsFrozen = false;
  20418. return this;
  20419. };
  20420. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20421. /**
  20422. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20423. */
  20424. set: function (count) {
  20425. this._overridenInstanceCount = count;
  20426. },
  20427. enumerable: true,
  20428. configurable: true
  20429. });
  20430. // Methods
  20431. Mesh.prototype._preActivate = function () {
  20432. var sceneRenderId = this.getScene().getRenderId();
  20433. if (this._preActivateId === sceneRenderId) {
  20434. return this;
  20435. }
  20436. this._preActivateId = sceneRenderId;
  20437. this._visibleInstances = null;
  20438. return this;
  20439. };
  20440. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20441. if (this._visibleInstances) {
  20442. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20443. }
  20444. return this;
  20445. };
  20446. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20447. if (!this._visibleInstances) {
  20448. this._visibleInstances = {};
  20449. this._visibleInstances.defaultRenderId = renderId;
  20450. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20451. }
  20452. if (!this._visibleInstances[renderId]) {
  20453. this._visibleInstances[renderId] = new Array();
  20454. }
  20455. this._visibleInstances[renderId].push(instance);
  20456. return this;
  20457. };
  20458. /**
  20459. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20460. * This means the mesh underlying bounding box and sphere are recomputed.
  20461. * Returns the Mesh.
  20462. */
  20463. Mesh.prototype.refreshBoundingInfo = function () {
  20464. if (this._boundingInfo.isLocked) {
  20465. return;
  20466. }
  20467. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20468. if (data) {
  20469. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20470. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20471. }
  20472. if (this.subMeshes) {
  20473. for (var index = 0; index < this.subMeshes.length; index++) {
  20474. this.subMeshes[index].refreshBoundingInfo();
  20475. }
  20476. }
  20477. this._updateBoundingInfo();
  20478. return this;
  20479. };
  20480. Mesh.prototype._createGlobalSubMesh = function () {
  20481. var totalVertices = this.getTotalVertices();
  20482. if (!totalVertices || !this.getIndices()) {
  20483. return null;
  20484. }
  20485. // Check if we need to recreate the submeshes
  20486. if (this.subMeshes && this.subMeshes.length > 0) {
  20487. var totalIndices = this.getIndices().length;
  20488. var needToRecreate = false;
  20489. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20490. var submesh = _a[_i];
  20491. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  20492. needToRecreate = true;
  20493. break;
  20494. }
  20495. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  20496. needToRecreate = true;
  20497. break;
  20498. }
  20499. }
  20500. if (!needToRecreate) {
  20501. return;
  20502. }
  20503. }
  20504. this.releaseSubMeshes();
  20505. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20506. };
  20507. Mesh.prototype.subdivide = function (count) {
  20508. if (count < 1) {
  20509. return;
  20510. }
  20511. var totalIndices = this.getTotalIndices();
  20512. var subdivisionSize = (totalIndices / count) | 0;
  20513. var offset = 0;
  20514. // Ensure that subdivisionSize is a multiple of 3
  20515. while (subdivisionSize % 3 !== 0) {
  20516. subdivisionSize++;
  20517. }
  20518. this.releaseSubMeshes();
  20519. for (var index = 0; index < count; index++) {
  20520. if (offset >= totalIndices) {
  20521. break;
  20522. }
  20523. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20524. offset += subdivisionSize;
  20525. }
  20526. this.synchronizeInstances();
  20527. };
  20528. /**
  20529. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20530. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20531. * The `data` are either a numeric array either a Float32Array.
  20532. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20533. * 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).
  20534. * Note that a new underlying VertexBuffer object is created each call.
  20535. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20536. *
  20537. * Possible `kind` values :
  20538. * - BABYLON.VertexBuffer.PositionKind
  20539. * - BABYLON.VertexBuffer.UVKind
  20540. * - BABYLON.VertexBuffer.UV2Kind
  20541. * - BABYLON.VertexBuffer.UV3Kind
  20542. * - BABYLON.VertexBuffer.UV4Kind
  20543. * - BABYLON.VertexBuffer.UV5Kind
  20544. * - BABYLON.VertexBuffer.UV6Kind
  20545. * - BABYLON.VertexBuffer.ColorKind
  20546. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20547. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20548. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20549. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20550. *
  20551. * Returns the Mesh.
  20552. */
  20553. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20554. if (!this._geometry) {
  20555. var vertexData = new BABYLON.VertexData();
  20556. vertexData.set(data, kind);
  20557. var scene = this.getScene();
  20558. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20559. }
  20560. else {
  20561. this._geometry.setVerticesData(kind, data, updatable, stride);
  20562. }
  20563. return this;
  20564. };
  20565. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20566. if (updatable === void 0) { updatable = true; }
  20567. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20568. return;
  20569. }
  20570. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20571. };
  20572. /**
  20573. * Sets the mesh VertexBuffer.
  20574. * Returns the Mesh.
  20575. */
  20576. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20577. if (!this._geometry) {
  20578. var scene = this.getScene();
  20579. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20580. }
  20581. this._geometry.setVerticesBuffer(buffer);
  20582. return this;
  20583. };
  20584. /**
  20585. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20586. * If the mesh has no geometry, it is simply returned as it is.
  20587. * The `data` are either a numeric array either a Float32Array.
  20588. * No new underlying VertexBuffer object is created.
  20589. * 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.
  20590. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20591. *
  20592. * Possible `kind` values :
  20593. * - BABYLON.VertexBuffer.PositionKind
  20594. * - BABYLON.VertexBuffer.UVKind
  20595. * - BABYLON.VertexBuffer.UV2Kind
  20596. * - BABYLON.VertexBuffer.UV3Kind
  20597. * - BABYLON.VertexBuffer.UV4Kind
  20598. * - BABYLON.VertexBuffer.UV5Kind
  20599. * - BABYLON.VertexBuffer.UV6Kind
  20600. * - BABYLON.VertexBuffer.ColorKind
  20601. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20602. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20603. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20604. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20605. *
  20606. * Returns the Mesh.
  20607. */
  20608. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20609. if (!this._geometry) {
  20610. return;
  20611. }
  20612. if (!makeItUnique) {
  20613. this._geometry.updateVerticesData(kind, data, updateExtends);
  20614. }
  20615. else {
  20616. this.makeGeometryUnique();
  20617. this.updateVerticesData(kind, data, updateExtends, false);
  20618. }
  20619. return this;
  20620. };
  20621. /**
  20622. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20623. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20624. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20625. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20626. * Returns the Mesh.
  20627. */
  20628. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20629. if (computeNormals === void 0) { computeNormals = true; }
  20630. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20631. positionFunction(positions);
  20632. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20633. if (computeNormals) {
  20634. var indices = this.getIndices();
  20635. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20636. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20637. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20638. }
  20639. return this;
  20640. };
  20641. /**
  20642. * Creates a un-shared specific occurence of the geometry for the mesh.
  20643. * Returns the Mesh.
  20644. */
  20645. Mesh.prototype.makeGeometryUnique = function () {
  20646. if (!this._geometry) {
  20647. return;
  20648. }
  20649. var oldGeometry = this._geometry;
  20650. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20651. oldGeometry.releaseForMesh(this, true);
  20652. geometry.applyToMesh(this);
  20653. return this;
  20654. };
  20655. /**
  20656. * Sets the mesh indices.
  20657. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20658. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20659. * This method creates a new index buffer each call.
  20660. * Returns the Mesh.
  20661. */
  20662. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20663. if (!this._geometry) {
  20664. var vertexData = new BABYLON.VertexData();
  20665. vertexData.indices = indices;
  20666. var scene = this.getScene();
  20667. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20668. }
  20669. else {
  20670. this._geometry.setIndices(indices, totalVertices);
  20671. }
  20672. return this;
  20673. };
  20674. /**
  20675. * Invert the geometry to move from a right handed system to a left handed one.
  20676. * Returns the Mesh.
  20677. */
  20678. Mesh.prototype.toLeftHanded = function () {
  20679. if (!this._geometry) {
  20680. return;
  20681. }
  20682. this._geometry.toLeftHanded();
  20683. return this;
  20684. };
  20685. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20686. var engine = this.getScene().getEngine();
  20687. // Wireframe
  20688. var indexToBind;
  20689. if (this._unIndexed) {
  20690. indexToBind = null;
  20691. }
  20692. else {
  20693. switch (fillMode) {
  20694. case BABYLON.Material.PointFillMode:
  20695. indexToBind = null;
  20696. break;
  20697. case BABYLON.Material.WireFrameFillMode:
  20698. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20699. break;
  20700. default:
  20701. case BABYLON.Material.TriangleFillMode:
  20702. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20703. break;
  20704. }
  20705. }
  20706. // VBOs
  20707. this._geometry._bind(effect, indexToBind);
  20708. return this;
  20709. };
  20710. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20711. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20712. return this;
  20713. }
  20714. this.onBeforeDrawObservable.notifyObservers(this);
  20715. var engine = this.getScene().getEngine();
  20716. // Draw order
  20717. switch (fillMode) {
  20718. case BABYLON.Material.PointFillMode:
  20719. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20720. break;
  20721. case BABYLON.Material.WireFrameFillMode:
  20722. if (this._unIndexed) {
  20723. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20724. }
  20725. else {
  20726. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20727. }
  20728. break;
  20729. default:
  20730. if (this._unIndexed) {
  20731. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20732. }
  20733. else {
  20734. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20735. }
  20736. }
  20737. return this;
  20738. };
  20739. /**
  20740. * Registers for this mesh a javascript function called just before the rendering process.
  20741. * This function is passed the current mesh.
  20742. * Return the Mesh.
  20743. */
  20744. Mesh.prototype.registerBeforeRender = function (func) {
  20745. this.onBeforeRenderObservable.add(func);
  20746. return this;
  20747. };
  20748. /**
  20749. * Disposes a previously registered javascript function called before the rendering.
  20750. * This function is passed the current mesh.
  20751. * Returns the Mesh.
  20752. */
  20753. Mesh.prototype.unregisterBeforeRender = function (func) {
  20754. this.onBeforeRenderObservable.removeCallback(func);
  20755. return this;
  20756. };
  20757. /**
  20758. * Registers for this mesh a javascript function called just after the rendering is complete.
  20759. * This function is passed the current mesh.
  20760. * Returns the Mesh.
  20761. */
  20762. Mesh.prototype.registerAfterRender = function (func) {
  20763. this.onAfterRenderObservable.add(func);
  20764. return this;
  20765. };
  20766. /**
  20767. * Disposes a previously registered javascript function called after the rendering.
  20768. * This function is passed the current mesh.
  20769. * Return the Mesh.
  20770. */
  20771. Mesh.prototype.unregisterAfterRender = function (func) {
  20772. this.onAfterRenderObservable.removeCallback(func);
  20773. return this;
  20774. };
  20775. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20776. var scene = this.getScene();
  20777. this._batchCache.mustReturn = false;
  20778. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20779. this._batchCache.visibleInstances[subMeshId] = null;
  20780. if (this._visibleInstances) {
  20781. var currentRenderId = scene.getRenderId();
  20782. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20783. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20784. var selfRenderId = this._renderId;
  20785. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20786. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20787. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20788. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20789. }
  20790. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20791. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20792. this._batchCache.mustReturn = true;
  20793. return this._batchCache;
  20794. }
  20795. if (currentRenderId !== selfRenderId) {
  20796. this._batchCache.renderSelf[subMeshId] = false;
  20797. }
  20798. }
  20799. this._renderIdForInstances[subMeshId] = currentRenderId;
  20800. }
  20801. return this._batchCache;
  20802. };
  20803. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20804. var visibleInstances = batch.visibleInstances[subMesh._id];
  20805. var matricesCount = visibleInstances.length + 1;
  20806. var bufferSize = matricesCount * 16 * 4;
  20807. var currentInstancesBufferSize = this._instancesBufferSize;
  20808. var instancesBuffer = this._instancesBuffer;
  20809. while (this._instancesBufferSize < bufferSize) {
  20810. this._instancesBufferSize *= 2;
  20811. }
  20812. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20813. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20814. }
  20815. var offset = 0;
  20816. var instancesCount = 0;
  20817. var world = this.getWorldMatrix();
  20818. if (batch.renderSelf[subMesh._id]) {
  20819. world.copyToArray(this._instancesData, offset);
  20820. offset += 16;
  20821. instancesCount++;
  20822. }
  20823. if (visibleInstances) {
  20824. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20825. var instance = visibleInstances[instanceIndex];
  20826. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20827. offset += 16;
  20828. instancesCount++;
  20829. }
  20830. }
  20831. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20832. if (instancesBuffer) {
  20833. instancesBuffer.dispose();
  20834. }
  20835. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20836. this._instancesBuffer = instancesBuffer;
  20837. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20838. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20839. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20840. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20841. }
  20842. else {
  20843. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20844. }
  20845. this.geometry._bind(effect);
  20846. this._draw(subMesh, fillMode, instancesCount);
  20847. engine.unbindInstanceAttributes();
  20848. return this;
  20849. };
  20850. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20851. var scene = this.getScene();
  20852. var engine = scene.getEngine();
  20853. if (hardwareInstancedRendering) {
  20854. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20855. }
  20856. else {
  20857. if (batch.renderSelf[subMesh._id]) {
  20858. // Draw
  20859. if (onBeforeDraw) {
  20860. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20861. }
  20862. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20863. }
  20864. if (batch.visibleInstances[subMesh._id]) {
  20865. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20866. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20867. // World
  20868. var world = instance.getWorldMatrix();
  20869. if (onBeforeDraw) {
  20870. onBeforeDraw(true, world, effectiveMaterial);
  20871. }
  20872. // Draw
  20873. this._draw(subMesh, fillMode);
  20874. }
  20875. }
  20876. }
  20877. return this;
  20878. };
  20879. /**
  20880. * Triggers the draw call for the mesh.
  20881. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20882. * Returns the Mesh.
  20883. */
  20884. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20885. var scene = this.getScene();
  20886. // Managing instances
  20887. var batch = this._getInstancesRenderList(subMesh._id);
  20888. if (batch.mustReturn) {
  20889. return this;
  20890. }
  20891. // Checking geometry state
  20892. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20893. return this;
  20894. }
  20895. var callbackIndex;
  20896. this.onBeforeRenderObservable.notifyObservers(this);
  20897. var engine = scene.getEngine();
  20898. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20899. // Material
  20900. var effectiveMaterial = subMesh.getMaterial();
  20901. if (!effectiveMaterial) {
  20902. return this;
  20903. }
  20904. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20905. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20906. return this;
  20907. }
  20908. }
  20909. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20910. return this;
  20911. }
  20912. // Alpha mode
  20913. if (enableAlphaMode) {
  20914. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20915. }
  20916. // Outline - step 1
  20917. var savedDepthWrite = engine.getDepthWrite();
  20918. if (this.renderOutline) {
  20919. engine.setDepthWrite(false);
  20920. scene.getOutlineRenderer().render(subMesh, batch);
  20921. engine.setDepthWrite(savedDepthWrite);
  20922. }
  20923. var effect;
  20924. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20925. effect = subMesh.effect;
  20926. }
  20927. else {
  20928. effect = effectiveMaterial.getEffect();
  20929. }
  20930. effectiveMaterial._preBind(effect);
  20931. // Bind
  20932. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20933. this._bind(subMesh, effect, fillMode);
  20934. var world = this.getWorldMatrix();
  20935. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20936. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20937. }
  20938. else {
  20939. effectiveMaterial.bind(world, this);
  20940. }
  20941. // Draw
  20942. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20943. // Unbind
  20944. effectiveMaterial.unbind();
  20945. // Outline - step 2
  20946. if (this.renderOutline && savedDepthWrite) {
  20947. engine.setDepthWrite(true);
  20948. engine.setColorWrite(false);
  20949. scene.getOutlineRenderer().render(subMesh, batch);
  20950. engine.setColorWrite(true);
  20951. }
  20952. // Overlay
  20953. if (this.renderOverlay) {
  20954. var currentMode = engine.getAlphaMode();
  20955. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20956. scene.getOutlineRenderer().render(subMesh, batch, true);
  20957. engine.setAlphaMode(currentMode);
  20958. }
  20959. this.onAfterRenderObservable.notifyObservers(this);
  20960. return this;
  20961. };
  20962. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20963. if (isInstance) {
  20964. effectiveMaterial.bindOnlyWorldMatrix(world);
  20965. }
  20966. return this;
  20967. };
  20968. /**
  20969. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20970. */
  20971. Mesh.prototype.getEmittedParticleSystems = function () {
  20972. var results = new Array();
  20973. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20974. var particleSystem = this.getScene().particleSystems[index];
  20975. if (particleSystem.emitter === this) {
  20976. results.push(particleSystem);
  20977. }
  20978. }
  20979. return results;
  20980. };
  20981. /**
  20982. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20983. */
  20984. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20985. var results = new Array();
  20986. var descendants = this.getDescendants();
  20987. descendants.push(this);
  20988. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20989. var particleSystem = this.getScene().particleSystems[index];
  20990. var emitter = particleSystem.emitter;
  20991. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  20992. results.push(particleSystem);
  20993. }
  20994. }
  20995. return results;
  20996. };
  20997. Mesh.prototype._checkDelayState = function () {
  20998. var scene = this.getScene();
  20999. if (this._geometry) {
  21000. this._geometry.load(scene);
  21001. }
  21002. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21003. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21004. this._queueLoad(this, scene);
  21005. }
  21006. return this;
  21007. };
  21008. Mesh.prototype._queueLoad = function (mesh, scene) {
  21009. var _this = this;
  21010. scene._addPendingData(mesh);
  21011. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21012. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21013. if (data instanceof ArrayBuffer) {
  21014. _this._delayLoadingFunction(data, _this);
  21015. }
  21016. else {
  21017. _this._delayLoadingFunction(JSON.parse(data), _this);
  21018. }
  21019. _this.instances.forEach(function (instance) {
  21020. instance._syncSubMeshes();
  21021. });
  21022. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21023. scene._removePendingData(_this);
  21024. }, function () { }, scene.database, getBinaryData);
  21025. return this;
  21026. };
  21027. /**
  21028. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21029. */
  21030. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21031. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21032. return false;
  21033. }
  21034. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21035. return false;
  21036. }
  21037. this._checkDelayState();
  21038. return true;
  21039. };
  21040. /**
  21041. * Sets the mesh material by the material or multiMaterial `id` property.
  21042. * The material `id` is a string identifying the material or the multiMaterial.
  21043. * This method returns the Mesh.
  21044. */
  21045. Mesh.prototype.setMaterialByID = function (id) {
  21046. var materials = this.getScene().materials;
  21047. var index;
  21048. for (index = materials.length - 1; index > -1; index--) {
  21049. if (materials[index].id === id) {
  21050. this.material = materials[index];
  21051. return this;
  21052. }
  21053. }
  21054. // Multi
  21055. var multiMaterials = this.getScene().multiMaterials;
  21056. for (index = multiMaterials.length - 1; index > -1; index--) {
  21057. if (multiMaterials[index].id === id) {
  21058. this.material = multiMaterials[index];
  21059. return this;
  21060. }
  21061. }
  21062. return this;
  21063. };
  21064. /**
  21065. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21066. */
  21067. Mesh.prototype.getAnimatables = function () {
  21068. var results = [];
  21069. if (this.material) {
  21070. results.push(this.material);
  21071. }
  21072. if (this.skeleton) {
  21073. results.push(this.skeleton);
  21074. }
  21075. return results;
  21076. };
  21077. /**
  21078. * Modifies the mesh geometry according to the passed transformation matrix.
  21079. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21080. * The mesh normals are modified accordingly the same transformation.
  21081. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21082. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21083. * Returns the Mesh.
  21084. */
  21085. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21086. // Position
  21087. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21088. return this;
  21089. }
  21090. var submeshes = this.subMeshes.splice(0);
  21091. this._resetPointsArrayCache();
  21092. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21093. var temp = [];
  21094. var index;
  21095. for (index = 0; index < data.length; index += 3) {
  21096. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21097. }
  21098. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21099. // Normals
  21100. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21101. return this;
  21102. }
  21103. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21104. temp = [];
  21105. for (index = 0; index < data.length; index += 3) {
  21106. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  21107. }
  21108. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  21109. // flip faces?
  21110. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  21111. this.flipFaces();
  21112. }
  21113. // Restore submeshes
  21114. this.releaseSubMeshes();
  21115. this.subMeshes = submeshes;
  21116. return this;
  21117. };
  21118. /**
  21119. * Modifies the mesh geometry according to its own current World Matrix.
  21120. * The mesh World Matrix is then reset.
  21121. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  21122. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21123. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21124. * Returns the Mesh.
  21125. */
  21126. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  21127. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  21128. this.scaling.copyFromFloats(1, 1, 1);
  21129. this.position.copyFromFloats(0, 0, 0);
  21130. this.rotation.copyFromFloats(0, 0, 0);
  21131. //only if quaternion is already set
  21132. if (this.rotationQuaternion) {
  21133. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  21134. }
  21135. this._worldMatrix = BABYLON.Matrix.Identity();
  21136. return this;
  21137. };
  21138. Object.defineProperty(Mesh.prototype, "_positions", {
  21139. // Cache
  21140. get: function () {
  21141. if (this._geometry) {
  21142. return this._geometry._positions;
  21143. }
  21144. return null;
  21145. },
  21146. enumerable: true,
  21147. configurable: true
  21148. });
  21149. Mesh.prototype._resetPointsArrayCache = function () {
  21150. if (this._geometry) {
  21151. this._geometry._resetPointsArrayCache();
  21152. }
  21153. return this;
  21154. };
  21155. Mesh.prototype._generatePointsArray = function () {
  21156. if (this._geometry) {
  21157. return this._geometry._generatePointsArray();
  21158. }
  21159. return false;
  21160. };
  21161. /**
  21162. * Returns a new Mesh object generated from the current mesh properties.
  21163. * This method must not get confused with createInstance().
  21164. * The parameter `name` is a string, the name given to the new mesh.
  21165. * The optional parameter `newParent` can be any Node object (default `null`).
  21166. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  21167. * 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.
  21168. */
  21169. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  21170. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21171. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  21172. };
  21173. /**
  21174. * Disposes the mesh.
  21175. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  21176. */
  21177. Mesh.prototype.dispose = function (doNotRecurse) {
  21178. var _this = this;
  21179. this.morphTargetManager = undefined;
  21180. if (this._geometry) {
  21181. this._geometry.releaseForMesh(this, true);
  21182. }
  21183. // Sources
  21184. var meshes = this.getScene().meshes;
  21185. meshes.forEach(function (mesh) {
  21186. if (mesh._source && mesh._source === _this) {
  21187. mesh._source = null;
  21188. }
  21189. });
  21190. this._source = null;
  21191. // Instances
  21192. if (this._instancesBuffer) {
  21193. this._instancesBuffer.dispose();
  21194. this._instancesBuffer = null;
  21195. }
  21196. while (this.instances.length) {
  21197. this.instances[0].dispose();
  21198. }
  21199. // Highlight layers.
  21200. var highlightLayers = this.getScene().highlightLayers;
  21201. for (var i = 0; i < highlightLayers.length; i++) {
  21202. var highlightLayer = highlightLayers[i];
  21203. if (highlightLayer) {
  21204. highlightLayer.removeMesh(this);
  21205. highlightLayer.removeExcludedMesh(this);
  21206. }
  21207. }
  21208. _super.prototype.dispose.call(this, doNotRecurse);
  21209. };
  21210. /**
  21211. * Modifies the mesh geometry according to a displacement map.
  21212. * 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.
  21213. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21214. * This method returns nothing.
  21215. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21216. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21217. * 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.
  21218. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21219. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21220. *
  21221. * Returns the Mesh.
  21222. */
  21223. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21224. var _this = this;
  21225. var scene = this.getScene();
  21226. var onload = function (img) {
  21227. // Getting height map data
  21228. var canvas = document.createElement("canvas");
  21229. var context = canvas.getContext("2d");
  21230. var heightMapWidth = img.width;
  21231. var heightMapHeight = img.height;
  21232. canvas.width = heightMapWidth;
  21233. canvas.height = heightMapHeight;
  21234. context.drawImage(img, 0, 0);
  21235. // Create VertexData from map data
  21236. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21237. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21238. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21239. //execute success callback, if set
  21240. if (onSuccess) {
  21241. onSuccess(_this);
  21242. }
  21243. };
  21244. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21245. return this;
  21246. };
  21247. /**
  21248. * Modifies the mesh geometry according to a displacementMap buffer.
  21249. * 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.
  21250. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21251. * This method returns nothing.
  21252. * 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.
  21253. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21254. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21255. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21256. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21257. *
  21258. * Returns the Mesh.
  21259. */
  21260. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21261. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21262. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21263. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21264. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21265. return this;
  21266. }
  21267. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21268. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21269. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21270. var position = BABYLON.Vector3.Zero();
  21271. var normal = BABYLON.Vector3.Zero();
  21272. var uv = BABYLON.Vector2.Zero();
  21273. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21274. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21275. for (var index = 0; index < positions.length; index += 3) {
  21276. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21277. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21278. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21279. // Compute height
  21280. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21281. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21282. var pos = (u + v * heightMapWidth) * 4;
  21283. var r = buffer[pos] / 255.0;
  21284. var g = buffer[pos + 1] / 255.0;
  21285. var b = buffer[pos + 2] / 255.0;
  21286. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21287. normal.normalize();
  21288. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21289. position = position.add(normal);
  21290. position.toArray(positions, index);
  21291. }
  21292. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21293. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21294. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21295. return this;
  21296. };
  21297. /**
  21298. * Modify the mesh to get a flat shading rendering.
  21299. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21300. * This method returns the Mesh.
  21301. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21302. */
  21303. Mesh.prototype.convertToFlatShadedMesh = function () {
  21304. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21305. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21306. var kinds = this.getVerticesDataKinds();
  21307. var vbs = [];
  21308. var data = [];
  21309. var newdata = [];
  21310. var updatableNormals = false;
  21311. var kindIndex;
  21312. var kind;
  21313. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21314. kind = kinds[kindIndex];
  21315. var vertexBuffer = this.getVertexBuffer(kind);
  21316. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21317. updatableNormals = vertexBuffer.isUpdatable();
  21318. kinds.splice(kindIndex, 1);
  21319. kindIndex--;
  21320. continue;
  21321. }
  21322. vbs[kind] = vertexBuffer;
  21323. data[kind] = vbs[kind].getData();
  21324. newdata[kind] = [];
  21325. }
  21326. // Save previous submeshes
  21327. var previousSubmeshes = this.subMeshes.slice(0);
  21328. var indices = this.getIndices();
  21329. var totalIndices = this.getTotalIndices();
  21330. // Generating unique vertices per face
  21331. var index;
  21332. for (index = 0; index < totalIndices; index++) {
  21333. var vertexIndex = indices[index];
  21334. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21335. kind = kinds[kindIndex];
  21336. var stride = vbs[kind].getStrideSize();
  21337. for (var offset = 0; offset < stride; offset++) {
  21338. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21339. }
  21340. }
  21341. }
  21342. // Updating faces & normal
  21343. var normals = [];
  21344. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21345. for (index = 0; index < totalIndices; index += 3) {
  21346. indices[index] = index;
  21347. indices[index + 1] = index + 1;
  21348. indices[index + 2] = index + 2;
  21349. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21350. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21351. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21352. var p1p2 = p1.subtract(p2);
  21353. var p3p2 = p3.subtract(p2);
  21354. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21355. // Store same normals for every vertex
  21356. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21357. normals.push(normal.x);
  21358. normals.push(normal.y);
  21359. normals.push(normal.z);
  21360. }
  21361. }
  21362. this.setIndices(indices);
  21363. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21364. // Updating vertex buffers
  21365. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21366. kind = kinds[kindIndex];
  21367. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21368. }
  21369. // Updating submeshes
  21370. this.releaseSubMeshes();
  21371. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21372. var previousOne = previousSubmeshes[submeshIndex];
  21373. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21374. }
  21375. this.synchronizeInstances();
  21376. return this;
  21377. };
  21378. /**
  21379. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21380. * In other words, more vertices, no more indices and a single bigger VBO.
  21381. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21382. * Returns the Mesh.
  21383. */
  21384. Mesh.prototype.convertToUnIndexedMesh = function () {
  21385. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21386. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21387. var kinds = this.getVerticesDataKinds();
  21388. var vbs = [];
  21389. var data = [];
  21390. var newdata = [];
  21391. var updatableNormals = false;
  21392. var kindIndex;
  21393. var kind;
  21394. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21395. kind = kinds[kindIndex];
  21396. var vertexBuffer = this.getVertexBuffer(kind);
  21397. vbs[kind] = vertexBuffer;
  21398. data[kind] = vbs[kind].getData();
  21399. newdata[kind] = [];
  21400. }
  21401. // Save previous submeshes
  21402. var previousSubmeshes = this.subMeshes.slice(0);
  21403. var indices = this.getIndices();
  21404. var totalIndices = this.getTotalIndices();
  21405. // Generating unique vertices per face
  21406. var index;
  21407. for (index = 0; index < totalIndices; index++) {
  21408. var vertexIndex = indices[index];
  21409. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21410. kind = kinds[kindIndex];
  21411. var stride = vbs[kind].getStrideSize();
  21412. for (var offset = 0; offset < stride; offset++) {
  21413. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21414. }
  21415. }
  21416. }
  21417. // Updating indices
  21418. for (index = 0; index < totalIndices; index += 3) {
  21419. indices[index] = index;
  21420. indices[index + 1] = index + 1;
  21421. indices[index + 2] = index + 2;
  21422. }
  21423. this.setIndices(indices);
  21424. // Updating vertex buffers
  21425. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21426. kind = kinds[kindIndex];
  21427. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21428. }
  21429. // Updating submeshes
  21430. this.releaseSubMeshes();
  21431. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21432. var previousOne = previousSubmeshes[submeshIndex];
  21433. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21434. }
  21435. this._unIndexed = true;
  21436. this.synchronizeInstances();
  21437. return this;
  21438. };
  21439. /**
  21440. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21441. * This method returns the Mesh.
  21442. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21443. */
  21444. Mesh.prototype.flipFaces = function (flipNormals) {
  21445. if (flipNormals === void 0) { flipNormals = false; }
  21446. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21447. var i;
  21448. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21449. for (i = 0; i < vertex_data.normals.length; i++) {
  21450. vertex_data.normals[i] *= -1;
  21451. }
  21452. }
  21453. var temp;
  21454. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21455. // reassign indices
  21456. temp = vertex_data.indices[i + 1];
  21457. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21458. vertex_data.indices[i + 2] = temp;
  21459. }
  21460. vertex_data.applyToMesh(this);
  21461. return this;
  21462. };
  21463. // Instances
  21464. /**
  21465. * Creates a new InstancedMesh object from the mesh model.
  21466. * An instance shares the same properties and the same material than its model.
  21467. * Only these properties of each instance can then be set individually :
  21468. * - position
  21469. * - rotation
  21470. * - rotationQuaternion
  21471. * - setPivotMatrix
  21472. * - scaling
  21473. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21474. * Warning : this method is not supported for Line mesh and LineSystem
  21475. */
  21476. Mesh.prototype.createInstance = function (name) {
  21477. return new BABYLON.InstancedMesh(name, this);
  21478. };
  21479. /**
  21480. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21481. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21482. * This method returns the Mesh.
  21483. */
  21484. Mesh.prototype.synchronizeInstances = function () {
  21485. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21486. var instance = this.instances[instanceIndex];
  21487. instance._syncSubMeshes();
  21488. }
  21489. return this;
  21490. };
  21491. /**
  21492. * Simplify the mesh according to the given array of settings.
  21493. * Function will return immediately and will simplify async. It returns the Mesh.
  21494. * @param settings a collection of simplification settings.
  21495. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21496. * @param type the type of simplification to run.
  21497. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21498. */
  21499. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21500. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21501. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21502. this.getScene().simplificationQueue.addTask({
  21503. settings: settings,
  21504. parallelProcessing: parallelProcessing,
  21505. mesh: this,
  21506. simplificationType: simplificationType,
  21507. successCallback: successCallback
  21508. });
  21509. return this;
  21510. };
  21511. /**
  21512. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21513. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21514. * This should be used together with the simplification to avoid disappearing triangles.
  21515. * Returns the Mesh.
  21516. * @param successCallback an optional success callback to be called after the optimization finished.
  21517. */
  21518. Mesh.prototype.optimizeIndices = function (successCallback) {
  21519. var _this = this;
  21520. var indices = this.getIndices();
  21521. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21522. var vectorPositions = [];
  21523. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21524. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21525. }
  21526. var dupes = [];
  21527. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21528. var realPos = vectorPositions.length - 1 - iteration;
  21529. var testedPosition = vectorPositions[realPos];
  21530. for (var j = 0; j < realPos; ++j) {
  21531. var againstPosition = vectorPositions[j];
  21532. if (testedPosition.equals(againstPosition)) {
  21533. dupes[realPos] = j;
  21534. break;
  21535. }
  21536. }
  21537. }, function () {
  21538. for (var i = 0; i < indices.length; ++i) {
  21539. indices[i] = dupes[indices[i]] || indices[i];
  21540. }
  21541. //indices are now reordered
  21542. var originalSubMeshes = _this.subMeshes.slice(0);
  21543. _this.setIndices(indices);
  21544. _this.subMeshes = originalSubMeshes;
  21545. if (successCallback) {
  21546. successCallback(_this);
  21547. }
  21548. });
  21549. return this;
  21550. };
  21551. Mesh.prototype.serialize = function (serializationObject) {
  21552. serializationObject.name = this.name;
  21553. serializationObject.id = this.id;
  21554. serializationObject.type = this.getClassName();
  21555. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21556. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21557. }
  21558. serializationObject.position = this.position.asArray();
  21559. if (this.rotationQuaternion) {
  21560. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21561. }
  21562. else if (this.rotation) {
  21563. serializationObject.rotation = this.rotation.asArray();
  21564. }
  21565. serializationObject.scaling = this.scaling.asArray();
  21566. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21567. serializationObject.isEnabled = this.isEnabled();
  21568. serializationObject.isVisible = this.isVisible;
  21569. serializationObject.infiniteDistance = this.infiniteDistance;
  21570. serializationObject.pickable = this.isPickable;
  21571. serializationObject.receiveShadows = this.receiveShadows;
  21572. serializationObject.billboardMode = this.billboardMode;
  21573. serializationObject.visibility = this.visibility;
  21574. serializationObject.checkCollisions = this.checkCollisions;
  21575. serializationObject.isBlocker = this.isBlocker;
  21576. // Parent
  21577. if (this.parent) {
  21578. serializationObject.parentId = this.parent.id;
  21579. }
  21580. // Geometry
  21581. var geometry = this._geometry;
  21582. if (geometry) {
  21583. var geometryId = geometry.id;
  21584. serializationObject.geometryId = geometryId;
  21585. // SubMeshes
  21586. serializationObject.subMeshes = [];
  21587. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21588. var subMesh = this.subMeshes[subIndex];
  21589. serializationObject.subMeshes.push({
  21590. materialIndex: subMesh.materialIndex,
  21591. verticesStart: subMesh.verticesStart,
  21592. verticesCount: subMesh.verticesCount,
  21593. indexStart: subMesh.indexStart,
  21594. indexCount: subMesh.indexCount
  21595. });
  21596. }
  21597. }
  21598. // Material
  21599. if (this.material) {
  21600. serializationObject.materialId = this.material.id;
  21601. }
  21602. else {
  21603. this.material = null;
  21604. }
  21605. // Morph targets
  21606. if (this.morphTargetManager) {
  21607. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21608. }
  21609. // Skeleton
  21610. if (this.skeleton) {
  21611. serializationObject.skeletonId = this.skeleton.id;
  21612. }
  21613. // Physics
  21614. //TODO implement correct serialization for physics impostors.
  21615. if (this.getPhysicsImpostor()) {
  21616. var impostor = this.getPhysicsImpostor();
  21617. serializationObject.physicsMass = impostor.getParam("mass");
  21618. serializationObject.physicsFriction = impostor.getParam("friction");
  21619. serializationObject.physicsRestitution = impostor.getParam("mass");
  21620. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21621. }
  21622. // Metadata
  21623. if (this.metadata) {
  21624. serializationObject.metadata = this.metadata;
  21625. }
  21626. // Instances
  21627. serializationObject.instances = [];
  21628. for (var index = 0; index < this.instances.length; index++) {
  21629. var instance = this.instances[index];
  21630. var serializationInstance = {
  21631. name: instance.name,
  21632. position: instance.position.asArray(),
  21633. scaling: instance.scaling.asArray()
  21634. };
  21635. if (instance.rotationQuaternion) {
  21636. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21637. }
  21638. else if (instance.rotation) {
  21639. serializationInstance.rotation = instance.rotation.asArray();
  21640. }
  21641. serializationObject.instances.push(serializationInstance);
  21642. // Animations
  21643. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21644. serializationInstance.ranges = instance.serializeAnimationRanges();
  21645. }
  21646. //
  21647. // Animations
  21648. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21649. serializationObject.ranges = this.serializeAnimationRanges();
  21650. // Layer mask
  21651. serializationObject.layerMask = this.layerMask;
  21652. // Alpha
  21653. serializationObject.alphaIndex = this.alphaIndex;
  21654. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21655. // Overlay
  21656. serializationObject.overlayAlpha = this.overlayAlpha;
  21657. serializationObject.overlayColor = this.overlayColor.asArray();
  21658. serializationObject.renderOverlay = this.renderOverlay;
  21659. // Fog
  21660. serializationObject.applyFog = this.applyFog;
  21661. // Action Manager
  21662. if (this.actionManager) {
  21663. serializationObject.actions = this.actionManager.serialize(this.name);
  21664. }
  21665. };
  21666. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21667. if (!this.geometry) {
  21668. return;
  21669. }
  21670. this._markSubMeshesAsAttributesDirty();
  21671. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21672. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21673. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21674. this.morphTargetManager = undefined;
  21675. return;
  21676. }
  21677. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21678. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21679. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21680. if (morphTarget.hasNormals) {
  21681. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21682. }
  21683. if (morphTarget.hasTangents) {
  21684. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21685. }
  21686. }
  21687. }
  21688. else {
  21689. var index = 0;
  21690. // Positions
  21691. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21692. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21693. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21694. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21695. }
  21696. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21697. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21698. }
  21699. index++;
  21700. }
  21701. }
  21702. };
  21703. // Statics
  21704. /**
  21705. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21706. * The parameter `parsedMesh` is the mesh to be copied.
  21707. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21708. */
  21709. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21710. var mesh;
  21711. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21712. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21713. }
  21714. else {
  21715. mesh = new Mesh(parsedMesh.name, scene);
  21716. }
  21717. mesh.id = parsedMesh.id;
  21718. if (BABYLON.Tags) {
  21719. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21720. }
  21721. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21722. if (parsedMesh.metadata !== undefined) {
  21723. mesh.metadata = parsedMesh.metadata;
  21724. }
  21725. if (parsedMesh.rotationQuaternion) {
  21726. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21727. }
  21728. else if (parsedMesh.rotation) {
  21729. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21730. }
  21731. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21732. if (parsedMesh.localMatrix) {
  21733. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21734. }
  21735. else if (parsedMesh.pivotMatrix) {
  21736. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21737. }
  21738. mesh.setEnabled(parsedMesh.isEnabled);
  21739. mesh.isVisible = parsedMesh.isVisible;
  21740. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21741. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21742. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21743. if (parsedMesh.applyFog !== undefined) {
  21744. mesh.applyFog = parsedMesh.applyFog;
  21745. }
  21746. if (parsedMesh.pickable !== undefined) {
  21747. mesh.isPickable = parsedMesh.pickable;
  21748. }
  21749. if (parsedMesh.alphaIndex !== undefined) {
  21750. mesh.alphaIndex = parsedMesh.alphaIndex;
  21751. }
  21752. mesh.receiveShadows = parsedMesh.receiveShadows;
  21753. mesh.billboardMode = parsedMesh.billboardMode;
  21754. if (parsedMesh.visibility !== undefined) {
  21755. mesh.visibility = parsedMesh.visibility;
  21756. }
  21757. mesh.checkCollisions = parsedMesh.checkCollisions;
  21758. if (parsedMesh.isBlocker !== undefined) {
  21759. mesh.isBlocker = parsedMesh.isBlocker;
  21760. }
  21761. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21762. // freezeWorldMatrix
  21763. if (parsedMesh.freezeWorldMatrix) {
  21764. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21765. }
  21766. // Parent
  21767. if (parsedMesh.parentId) {
  21768. mesh._waitingParentId = parsedMesh.parentId;
  21769. }
  21770. // Actions
  21771. if (parsedMesh.actions !== undefined) {
  21772. mesh._waitingActions = parsedMesh.actions;
  21773. }
  21774. // Overlay
  21775. if (parsedMesh.overlayAlpha !== undefined) {
  21776. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21777. }
  21778. if (parsedMesh.overlayColor !== undefined) {
  21779. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21780. }
  21781. if (parsedMesh.renderOverlay !== undefined) {
  21782. mesh.renderOverlay = parsedMesh.renderOverlay;
  21783. }
  21784. // Geometry
  21785. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21786. if (parsedMesh.delayLoadingFile) {
  21787. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21788. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21789. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21790. if (parsedMesh._binaryInfo) {
  21791. mesh._binaryInfo = parsedMesh._binaryInfo;
  21792. }
  21793. mesh._delayInfo = [];
  21794. if (parsedMesh.hasUVs) {
  21795. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21796. }
  21797. if (parsedMesh.hasUVs2) {
  21798. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21799. }
  21800. if (parsedMesh.hasUVs3) {
  21801. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21802. }
  21803. if (parsedMesh.hasUVs4) {
  21804. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21805. }
  21806. if (parsedMesh.hasUVs5) {
  21807. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21808. }
  21809. if (parsedMesh.hasUVs6) {
  21810. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21811. }
  21812. if (parsedMesh.hasColors) {
  21813. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21814. }
  21815. if (parsedMesh.hasMatricesIndices) {
  21816. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21817. }
  21818. if (parsedMesh.hasMatricesWeights) {
  21819. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21820. }
  21821. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21822. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21823. mesh._checkDelayState();
  21824. }
  21825. }
  21826. else {
  21827. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21828. }
  21829. // Material
  21830. if (parsedMesh.materialId) {
  21831. mesh.setMaterialByID(parsedMesh.materialId);
  21832. }
  21833. else {
  21834. mesh.material = null;
  21835. }
  21836. // Morph targets
  21837. if (parsedMesh.morphTargetManagerId > -1) {
  21838. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21839. }
  21840. // Skeleton
  21841. if (parsedMesh.skeletonId > -1) {
  21842. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21843. if (parsedMesh.numBoneInfluencers) {
  21844. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21845. }
  21846. }
  21847. // Animations
  21848. if (parsedMesh.animations) {
  21849. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21850. var parsedAnimation = parsedMesh.animations[animationIndex];
  21851. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21852. }
  21853. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21854. }
  21855. if (parsedMesh.autoAnimate) {
  21856. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21857. }
  21858. // Layer Mask
  21859. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21860. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21861. }
  21862. else {
  21863. mesh.layerMask = 0x0FFFFFFF;
  21864. }
  21865. // Physics
  21866. if (parsedMesh.physicsImpostor) {
  21867. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21868. mass: parsedMesh.physicsMass,
  21869. friction: parsedMesh.physicsFriction,
  21870. restitution: parsedMesh.physicsRestitution
  21871. }, scene);
  21872. }
  21873. // Instances
  21874. if (parsedMesh.instances) {
  21875. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21876. var parsedInstance = parsedMesh.instances[index];
  21877. var instance = mesh.createInstance(parsedInstance.name);
  21878. if (BABYLON.Tags) {
  21879. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21880. }
  21881. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21882. if (parsedInstance.parentId) {
  21883. instance._waitingParentId = parsedInstance.parentId;
  21884. }
  21885. if (parsedInstance.rotationQuaternion) {
  21886. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21887. }
  21888. else if (parsedInstance.rotation) {
  21889. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21890. }
  21891. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21892. instance.checkCollisions = mesh.checkCollisions;
  21893. if (parsedMesh.animations) {
  21894. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21895. parsedAnimation = parsedMesh.animations[animationIndex];
  21896. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21897. }
  21898. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21899. }
  21900. }
  21901. }
  21902. return mesh;
  21903. };
  21904. /**
  21905. * Creates a ribbon mesh.
  21906. * Please consider using the same method from the MeshBuilder class instead.
  21907. * 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.
  21908. *
  21909. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21910. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21911. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21912. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21913. * 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.
  21914. * 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.
  21915. * 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
  21916. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21917. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21919. */
  21920. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21921. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21922. pathArray: pathArray,
  21923. closeArray: closeArray,
  21924. closePath: closePath,
  21925. offset: offset,
  21926. updatable: updatable,
  21927. sideOrientation: sideOrientation,
  21928. instance: instance
  21929. }, scene);
  21930. };
  21931. /**
  21932. * Creates a plane polygonal mesh. By default, this is a disc.
  21933. * Please consider using the same method from the MeshBuilder class instead.
  21934. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21935. * 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.
  21936. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21937. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21939. */
  21940. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21941. var options = {
  21942. radius: radius,
  21943. tessellation: tessellation,
  21944. sideOrientation: sideOrientation,
  21945. updatable: updatable
  21946. };
  21947. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21948. };
  21949. /**
  21950. * Creates a box mesh.
  21951. * Please consider using the same method from the MeshBuilder class instead.
  21952. * The parameter `size` sets the size (float) of each box side (default 1).
  21953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21954. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21956. */
  21957. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21958. var options = {
  21959. size: size,
  21960. sideOrientation: sideOrientation,
  21961. updatable: updatable
  21962. };
  21963. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21964. };
  21965. /**
  21966. * Creates a sphere mesh.
  21967. * Please consider using the same method from the MeshBuilder class instead.
  21968. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21969. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21971. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21973. */
  21974. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21975. var options = {
  21976. segments: segments,
  21977. diameterX: diameter,
  21978. diameterY: diameter,
  21979. diameterZ: diameter,
  21980. sideOrientation: sideOrientation,
  21981. updatable: updatable
  21982. };
  21983. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21984. };
  21985. /**
  21986. * Creates a cylinder or a cone mesh.
  21987. * Please consider using the same method from the MeshBuilder class instead.
  21988. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21989. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21990. * 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.
  21991. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21992. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21994. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21996. */
  21997. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21998. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21999. if (scene !== undefined) {
  22000. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22001. updatable = scene;
  22002. }
  22003. scene = subdivisions;
  22004. subdivisions = 1;
  22005. }
  22006. var options = {
  22007. height: height,
  22008. diameterTop: diameterTop,
  22009. diameterBottom: diameterBottom,
  22010. tessellation: tessellation,
  22011. subdivisions: subdivisions,
  22012. sideOrientation: sideOrientation,
  22013. updatable: updatable
  22014. };
  22015. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22016. };
  22017. // Torus (Code from SharpDX.org)
  22018. /**
  22019. * Creates a torus mesh.
  22020. * Please consider using the same method from the MeshBuilder class instead.
  22021. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22022. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22023. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22024. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22027. */
  22028. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22029. var options = {
  22030. diameter: diameter,
  22031. thickness: thickness,
  22032. tessellation: tessellation,
  22033. sideOrientation: sideOrientation,
  22034. updatable: updatable
  22035. };
  22036. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22037. };
  22038. /**
  22039. * Creates a torus knot mesh.
  22040. * Please consider using the same method from the MeshBuilder class instead.
  22041. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22042. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22043. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22044. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22045. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22046. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22047. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22048. */
  22049. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22050. var options = {
  22051. radius: radius,
  22052. tube: tube,
  22053. radialSegments: radialSegments,
  22054. tubularSegments: tubularSegments,
  22055. p: p,
  22056. q: q,
  22057. sideOrientation: sideOrientation,
  22058. updatable: updatable
  22059. };
  22060. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22061. };
  22062. /**
  22063. * Creates a line mesh.
  22064. * Please consider using the same method from the MeshBuilder class instead.
  22065. * 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.
  22066. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22067. * The parameter `points` is an array successive Vector3.
  22068. * 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
  22069. * When updating an instance, remember that only point positions can change, not the number of points.
  22070. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22071. */
  22072. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22073. var options = {
  22074. points: points,
  22075. updatable: updatable,
  22076. instance: instance
  22077. };
  22078. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22079. };
  22080. /**
  22081. * Creates a dashed line mesh.
  22082. * Please consider using the same method from the MeshBuilder class instead.
  22083. * 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.
  22084. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22085. * The parameter `points` is an array successive Vector3.
  22086. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22087. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22088. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22089. * 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
  22090. * When updating an instance, remember that only point positions can change, not the number of points.
  22091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22092. */
  22093. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22094. var options = {
  22095. points: points,
  22096. dashSize: dashSize,
  22097. gapSize: gapSize,
  22098. dashNb: dashNb,
  22099. updatable: updatable,
  22100. instance: instance
  22101. };
  22102. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22103. };
  22104. /**
  22105. * Creates a polygon mesh.
  22106. * Please consider using the same method from the MeshBuilder class instead.
  22107. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  22108. * 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.
  22109. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22111. * Remember you can only change the shape positions, not their number when updating a polygon.
  22112. */
  22113. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  22114. var options = {
  22115. shape: shape,
  22116. holes: holes,
  22117. updatable: updatable,
  22118. sideOrientation: sideOrientation
  22119. };
  22120. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  22121. };
  22122. /**
  22123. * Creates an extruded polygon mesh, with depth in the Y direction.
  22124. * Please consider using the same method from the MeshBuilder class instead.
  22125. */
  22126. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  22127. var options = {
  22128. shape: shape,
  22129. holes: holes,
  22130. depth: depth,
  22131. updatable: updatable,
  22132. sideOrientation: sideOrientation
  22133. };
  22134. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  22135. };
  22136. /**
  22137. * Creates an extruded shape mesh.
  22138. * 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.
  22139. * Please consider using the same method from the MeshBuilder class instead.
  22140. *
  22141. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22142. * 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
  22143. * extruded along the Z axis.
  22144. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22145. * 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.
  22146. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22147. * 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
  22148. * 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
  22149. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22150. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22151. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22153. */
  22154. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  22155. var options = {
  22156. shape: shape,
  22157. path: path,
  22158. scale: scale,
  22159. rotation: rotation,
  22160. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22161. sideOrientation: sideOrientation,
  22162. instance: instance,
  22163. updatable: updatable
  22164. };
  22165. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  22166. };
  22167. /**
  22168. * Creates an custom extruded shape mesh.
  22169. * 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.
  22170. * Please consider using the same method from the MeshBuilder class instead.
  22171. *
  22172. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22173. * 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
  22174. * extruded along the Z axis.
  22175. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22176. * 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
  22177. * and the distance of this point from the begining of the path :
  22178. * ```javascript
  22179. * var rotationFunction = function(i, distance) {
  22180. * // do things
  22181. * return rotationValue; }
  22182. * ```
  22183. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22184. * 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
  22185. * and the distance of this point from the begining of the path :
  22186. * ```javascript
  22187. * var scaleFunction = function(i, distance) {
  22188. * // do things
  22189. * return scaleValue;}
  22190. * ```
  22191. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22192. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22193. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22194. * 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
  22195. * 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
  22196. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22197. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22198. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22199. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22200. */
  22201. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22202. var options = {
  22203. shape: shape,
  22204. path: path,
  22205. scaleFunction: scaleFunction,
  22206. rotationFunction: rotationFunction,
  22207. ribbonCloseArray: ribbonCloseArray,
  22208. ribbonClosePath: ribbonClosePath,
  22209. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22210. sideOrientation: sideOrientation,
  22211. instance: instance,
  22212. updatable: updatable
  22213. };
  22214. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22215. };
  22216. /**
  22217. * Creates lathe mesh.
  22218. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22219. * Please consider using the same method from the MeshBuilder class instead.
  22220. * 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
  22221. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22222. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22223. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22225. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22227. */
  22228. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22229. var options = {
  22230. shape: shape,
  22231. radius: radius,
  22232. tessellation: tessellation,
  22233. sideOrientation: sideOrientation,
  22234. updatable: updatable
  22235. };
  22236. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22237. };
  22238. /**
  22239. * Creates a plane mesh.
  22240. * Please consider using the same method from the MeshBuilder class instead.
  22241. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22242. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22243. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22245. */
  22246. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22247. var options = {
  22248. size: size,
  22249. width: size,
  22250. height: size,
  22251. sideOrientation: sideOrientation,
  22252. updatable: updatable
  22253. };
  22254. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22255. };
  22256. /**
  22257. * Creates a ground mesh.
  22258. * Please consider using the same method from the MeshBuilder class instead.
  22259. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22260. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22261. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22262. */
  22263. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22264. var options = {
  22265. width: width,
  22266. height: height,
  22267. subdivisions: subdivisions,
  22268. updatable: updatable
  22269. };
  22270. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22271. };
  22272. /**
  22273. * Creates a tiled ground mesh.
  22274. * Please consider using the same method from the MeshBuilder class instead.
  22275. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22276. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22277. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22278. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22279. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22280. * numbers of subdivisions on the ground width and height of each tile.
  22281. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22282. */
  22283. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22284. var options = {
  22285. xmin: xmin,
  22286. zmin: zmin,
  22287. xmax: xmax,
  22288. zmax: zmax,
  22289. subdivisions: subdivisions,
  22290. precision: precision,
  22291. updatable: updatable
  22292. };
  22293. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22294. };
  22295. /**
  22296. * Creates a ground mesh from a height map.
  22297. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22298. * Please consider using the same method from the MeshBuilder class instead.
  22299. * The parameter `url` sets the URL of the height map image resource.
  22300. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22301. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22302. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22303. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22304. * 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).
  22305. * This function is passed the newly built mesh :
  22306. * ```javascript
  22307. * function(mesh) { // do things
  22308. * return; }
  22309. * ```
  22310. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22311. */
  22312. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22313. var options = {
  22314. width: width,
  22315. height: height,
  22316. subdivisions: subdivisions,
  22317. minHeight: minHeight,
  22318. maxHeight: maxHeight,
  22319. updatable: updatable,
  22320. onReady: onReady
  22321. };
  22322. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22323. };
  22324. /**
  22325. * Creates a tube mesh.
  22326. * 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.
  22327. * Please consider using the same method from the MeshBuilder class instead.
  22328. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22329. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22330. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22331. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22332. * 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.
  22333. * It must return a radius value (positive float) :
  22334. * ```javascript
  22335. * var radiusFunction = function(i, distance) {
  22336. * // do things
  22337. * return radius; }
  22338. * ```
  22339. * 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
  22340. * 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
  22341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22342. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22344. */
  22345. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22346. var options = {
  22347. path: path,
  22348. radius: radius,
  22349. tessellation: tessellation,
  22350. radiusFunction: radiusFunction,
  22351. arc: 1,
  22352. cap: cap,
  22353. updatable: updatable,
  22354. sideOrientation: sideOrientation,
  22355. instance: instance
  22356. };
  22357. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22358. };
  22359. /**
  22360. * Creates a polyhedron mesh.
  22361. * Please consider using the same method from the MeshBuilder class instead.
  22362. * 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
  22363. * to choose the wanted type.
  22364. * The parameter `size` (positive float, default 1) sets the polygon size.
  22365. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22366. * 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`.
  22367. * 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
  22368. * 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)`).
  22369. * 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
  22370. * 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.
  22371. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22372. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22373. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22374. */
  22375. Mesh.CreatePolyhedron = function (name, options, scene) {
  22376. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22377. };
  22378. /**
  22379. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22380. * Please consider using the same method from the MeshBuilder class instead.
  22381. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22382. * 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`).
  22383. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22384. * 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.
  22385. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22386. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22387. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22388. */
  22389. Mesh.CreateIcoSphere = function (name, options, scene) {
  22390. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22391. };
  22392. /**
  22393. * Creates a decal mesh.
  22394. * Please consider using the same method from the MeshBuilder class instead.
  22395. * 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.
  22396. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22397. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22398. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22399. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22400. */
  22401. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22402. var options = {
  22403. position: position,
  22404. normal: normal,
  22405. size: size,
  22406. angle: angle
  22407. };
  22408. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22409. };
  22410. // Skeletons
  22411. /**
  22412. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22413. */
  22414. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22415. var source;
  22416. if (!this._sourcePositions) {
  22417. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22418. this._sourcePositions = new Float32Array(source);
  22419. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22420. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22421. }
  22422. }
  22423. return this._sourcePositions;
  22424. };
  22425. /**
  22426. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22427. */
  22428. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22429. var source;
  22430. if (!this._sourceNormals) {
  22431. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22432. this._sourceNormals = new Float32Array(source);
  22433. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22434. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22435. }
  22436. }
  22437. return this._sourceNormals;
  22438. };
  22439. /**
  22440. * Updates the vertex buffer by applying transformation from the bones.
  22441. * Returns the Mesh.
  22442. *
  22443. * @param {skeleton} skeleton to apply
  22444. */
  22445. Mesh.prototype.applySkeleton = function (skeleton) {
  22446. if (!this.geometry) {
  22447. return this;
  22448. }
  22449. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22450. return this;
  22451. }
  22452. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22453. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22454. return this;
  22455. }
  22456. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22457. return this;
  22458. }
  22459. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22460. return this;
  22461. }
  22462. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22463. return this;
  22464. }
  22465. if (!this._sourcePositions) {
  22466. var submeshes = this.subMeshes.slice();
  22467. this.setPositionsForCPUSkinning();
  22468. this.subMeshes = submeshes;
  22469. }
  22470. if (!this._sourceNormals) {
  22471. this.setNormalsForCPUSkinning();
  22472. }
  22473. // positionsData checks for not being Float32Array will only pass at most once
  22474. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22475. if (!(positionsData instanceof Float32Array)) {
  22476. positionsData = new Float32Array(positionsData);
  22477. }
  22478. // normalsData checks for not being Float32Array will only pass at most once
  22479. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22480. if (!(normalsData instanceof Float32Array)) {
  22481. normalsData = new Float32Array(normalsData);
  22482. }
  22483. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22484. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22485. var needExtras = this.numBoneInfluencers > 4;
  22486. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22487. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22488. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22489. var tempVector3 = BABYLON.Vector3.Zero();
  22490. var finalMatrix = new BABYLON.Matrix();
  22491. var tempMatrix = new BABYLON.Matrix();
  22492. var matWeightIdx = 0;
  22493. var inf;
  22494. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22495. var weight;
  22496. for (inf = 0; inf < 4; inf++) {
  22497. weight = matricesWeightsData[matWeightIdx + inf];
  22498. if (weight > 0) {
  22499. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22500. finalMatrix.addToSelf(tempMatrix);
  22501. }
  22502. else
  22503. break;
  22504. }
  22505. if (needExtras) {
  22506. for (inf = 0; inf < 4; inf++) {
  22507. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22508. if (weight > 0) {
  22509. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22510. finalMatrix.addToSelf(tempMatrix);
  22511. }
  22512. else
  22513. break;
  22514. }
  22515. }
  22516. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22517. tempVector3.toArray(positionsData, index);
  22518. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22519. tempVector3.toArray(normalsData, index);
  22520. finalMatrix.reset();
  22521. }
  22522. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22523. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22524. return this;
  22525. };
  22526. // Tools
  22527. /**
  22528. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22529. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22530. */
  22531. Mesh.MinMax = function (meshes) {
  22532. var minVector = null;
  22533. var maxVector = null;
  22534. meshes.forEach(function (mesh, index, array) {
  22535. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22536. if (!minVector) {
  22537. minVector = boundingBox.minimumWorld;
  22538. maxVector = boundingBox.maximumWorld;
  22539. }
  22540. else {
  22541. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22542. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22543. }
  22544. });
  22545. return {
  22546. min: minVector,
  22547. max: maxVector
  22548. };
  22549. };
  22550. /**
  22551. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22552. */
  22553. Mesh.Center = function (meshesOrMinMaxVector) {
  22554. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22555. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22556. };
  22557. /**
  22558. * Merge the array of meshes into a single mesh for performance reasons.
  22559. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22560. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22561. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22562. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22563. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22564. */
  22565. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22566. if (disposeSource === void 0) { disposeSource = true; }
  22567. var index;
  22568. if (!allow32BitsIndices) {
  22569. var totalVertices = 0;
  22570. // Counting vertices
  22571. for (index = 0; index < meshes.length; index++) {
  22572. if (meshes[index]) {
  22573. totalVertices += meshes[index].getTotalVertices();
  22574. if (totalVertices > 65536) {
  22575. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22576. return null;
  22577. }
  22578. }
  22579. }
  22580. }
  22581. // Merge
  22582. var vertexData;
  22583. var otherVertexData;
  22584. var indiceArray = new Array();
  22585. var source;
  22586. for (index = 0; index < meshes.length; index++) {
  22587. if (meshes[index]) {
  22588. meshes[index].computeWorldMatrix(true);
  22589. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22590. otherVertexData.transform(meshes[index].getWorldMatrix());
  22591. if (vertexData) {
  22592. vertexData.merge(otherVertexData);
  22593. }
  22594. else {
  22595. vertexData = otherVertexData;
  22596. source = meshes[index];
  22597. }
  22598. if (subdivideWithSubMeshes) {
  22599. indiceArray.push(meshes[index].getTotalIndices());
  22600. }
  22601. }
  22602. }
  22603. if (!meshSubclass) {
  22604. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22605. }
  22606. vertexData.applyToMesh(meshSubclass);
  22607. // Setting properties
  22608. meshSubclass.material = source.material;
  22609. meshSubclass.checkCollisions = source.checkCollisions;
  22610. // Cleaning
  22611. if (disposeSource) {
  22612. for (index = 0; index < meshes.length; index++) {
  22613. if (meshes[index]) {
  22614. meshes[index].dispose();
  22615. }
  22616. }
  22617. }
  22618. // Subdivide
  22619. if (subdivideWithSubMeshes) {
  22620. //-- Suppresions du submesh global
  22621. meshSubclass.releaseSubMeshes();
  22622. index = 0;
  22623. var offset = 0;
  22624. //-- aplique la subdivision en fonction du tableau d'indices
  22625. while (index < indiceArray.length) {
  22626. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22627. offset += indiceArray[index];
  22628. index++;
  22629. }
  22630. }
  22631. return meshSubclass;
  22632. };
  22633. return Mesh;
  22634. }(BABYLON.AbstractMesh));
  22635. // Consts
  22636. Mesh._FRONTSIDE = 0;
  22637. Mesh._BACKSIDE = 1;
  22638. Mesh._DOUBLESIDE = 2;
  22639. Mesh._DEFAULTSIDE = 0;
  22640. Mesh._NO_CAP = 0;
  22641. Mesh._CAP_START = 1;
  22642. Mesh._CAP_END = 2;
  22643. Mesh._CAP_ALL = 3;
  22644. BABYLON.Mesh = Mesh;
  22645. })(BABYLON || (BABYLON = {}));
  22646. //# sourceMappingURL=babylon.mesh.js.map
  22647. var BABYLON;
  22648. (function (BABYLON) {
  22649. var BaseSubMesh = (function () {
  22650. function BaseSubMesh() {
  22651. }
  22652. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  22653. get: function () {
  22654. return this._materialEffect;
  22655. },
  22656. enumerable: true,
  22657. configurable: true
  22658. });
  22659. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  22660. if (this._materialEffect === effect) {
  22661. return;
  22662. }
  22663. this._materialDefines = defines;
  22664. this._materialEffect = effect;
  22665. };
  22666. return BaseSubMesh;
  22667. }());
  22668. BABYLON.BaseSubMesh = BaseSubMesh;
  22669. var SubMesh = (function (_super) {
  22670. __extends(SubMesh, _super);
  22671. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22672. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22673. var _this = _super.call(this) || this;
  22674. _this.materialIndex = materialIndex;
  22675. _this.verticesStart = verticesStart;
  22676. _this.verticesCount = verticesCount;
  22677. _this.indexStart = indexStart;
  22678. _this.indexCount = indexCount;
  22679. _this._renderId = 0;
  22680. _this._mesh = mesh;
  22681. _this._renderingMesh = renderingMesh || mesh;
  22682. mesh.subMeshes.push(_this);
  22683. _this._trianglePlanes = [];
  22684. _this._id = mesh.subMeshes.length - 1;
  22685. if (createBoundingBox) {
  22686. _this.refreshBoundingInfo();
  22687. mesh.computeWorldMatrix(true);
  22688. }
  22689. return _this;
  22690. }
  22691. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22692. get: function () {
  22693. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22694. },
  22695. enumerable: true,
  22696. configurable: true
  22697. });
  22698. /**
  22699. * Returns the submesh BoudingInfo object.
  22700. */
  22701. SubMesh.prototype.getBoundingInfo = function () {
  22702. if (this.IsGlobal) {
  22703. return this._mesh.getBoundingInfo();
  22704. }
  22705. return this._boundingInfo;
  22706. };
  22707. /**
  22708. * Sets the submesh BoundingInfo.
  22709. * Return the SubMesh.
  22710. */
  22711. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22712. this._boundingInfo = boundingInfo;
  22713. return this;
  22714. };
  22715. /**
  22716. * Returns the mesh of the current submesh.
  22717. */
  22718. SubMesh.prototype.getMesh = function () {
  22719. return this._mesh;
  22720. };
  22721. /**
  22722. * Returns the rendering mesh of the submesh.
  22723. */
  22724. SubMesh.prototype.getRenderingMesh = function () {
  22725. return this._renderingMesh;
  22726. };
  22727. /**
  22728. * Returns the submesh material.
  22729. */
  22730. SubMesh.prototype.getMaterial = function () {
  22731. var rootMaterial = this._renderingMesh.material;
  22732. if (rootMaterial && rootMaterial.getSubMaterial) {
  22733. var multiMaterial = rootMaterial;
  22734. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22735. if (this._currentMaterial !== effectiveMaterial) {
  22736. this._currentMaterial = effectiveMaterial;
  22737. if (this._materialDefines) {
  22738. this._materialDefines.markAllAsDirty();
  22739. }
  22740. }
  22741. return effectiveMaterial;
  22742. }
  22743. if (!rootMaterial) {
  22744. return this._mesh.getScene().defaultMaterial;
  22745. }
  22746. return rootMaterial;
  22747. };
  22748. // Methods
  22749. /**
  22750. * Sets a new updated BoundingInfo object to the submesh.
  22751. * Returns the SubMesh.
  22752. */
  22753. SubMesh.prototype.refreshBoundingInfo = function () {
  22754. this._lastColliderWorldVertices = null;
  22755. if (this.IsGlobal) {
  22756. return;
  22757. }
  22758. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22759. if (!data) {
  22760. this._boundingInfo = this._mesh._boundingInfo;
  22761. return;
  22762. }
  22763. var indices = this._renderingMesh.getIndices();
  22764. var extend;
  22765. //is this the only submesh?
  22766. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22767. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22768. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22769. }
  22770. else {
  22771. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22772. }
  22773. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22774. return this;
  22775. };
  22776. SubMesh.prototype._checkCollision = function (collider) {
  22777. return this.getBoundingInfo()._checkCollision(collider);
  22778. };
  22779. /**
  22780. * Updates the submesh BoundingInfo.
  22781. * Returns the Submesh.
  22782. */
  22783. SubMesh.prototype.updateBoundingInfo = function (world) {
  22784. if (!this.getBoundingInfo()) {
  22785. this.refreshBoundingInfo();
  22786. }
  22787. this.getBoundingInfo().update(world);
  22788. return this;
  22789. };
  22790. /**
  22791. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22792. * Boolean returned.
  22793. */
  22794. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22795. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22796. };
  22797. /**
  22798. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22799. * Boolean returned.
  22800. */
  22801. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22802. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22803. };
  22804. /**
  22805. * Renders the submesh.
  22806. * Returns it.
  22807. */
  22808. SubMesh.prototype.render = function (enableAlphaMode) {
  22809. this._renderingMesh.render(this, enableAlphaMode);
  22810. return this;
  22811. };
  22812. /**
  22813. * Returns a new Index Buffer.
  22814. * Type returned : WebGLBuffer.
  22815. */
  22816. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22817. if (!this._linesIndexBuffer) {
  22818. var linesIndices = [];
  22819. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22820. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22821. }
  22822. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22823. this.linesIndexCount = linesIndices.length;
  22824. }
  22825. return this._linesIndexBuffer;
  22826. };
  22827. /**
  22828. * True is the passed Ray intersects the submesh bounding box.
  22829. * Boolean returned.
  22830. */
  22831. SubMesh.prototype.canIntersects = function (ray) {
  22832. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22833. };
  22834. /**
  22835. * Returns an object IntersectionInfo.
  22836. */
  22837. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22838. var intersectInfo = null;
  22839. // LineMesh first as it's also a Mesh...
  22840. if (this._mesh instanceof BABYLON.LinesMesh) {
  22841. var lineMesh = this._mesh;
  22842. // Line test
  22843. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22844. var p0 = positions[indices[index]];
  22845. var p1 = positions[indices[index + 1]];
  22846. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22847. if (length < 0) {
  22848. continue;
  22849. }
  22850. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22851. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22852. if (fastCheck) {
  22853. break;
  22854. }
  22855. }
  22856. }
  22857. }
  22858. else {
  22859. // Triangles test
  22860. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22861. var p0 = positions[indices[index]];
  22862. var p1 = positions[indices[index + 1]];
  22863. var p2 = positions[indices[index + 2]];
  22864. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22865. if (currentIntersectInfo) {
  22866. if (currentIntersectInfo.distance < 0) {
  22867. continue;
  22868. }
  22869. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22870. intersectInfo = currentIntersectInfo;
  22871. intersectInfo.faceId = index / 3;
  22872. if (fastCheck) {
  22873. break;
  22874. }
  22875. }
  22876. }
  22877. }
  22878. }
  22879. return intersectInfo;
  22880. };
  22881. // Clone
  22882. /**
  22883. * Creates a new Submesh from the passed Mesh.
  22884. */
  22885. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22886. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22887. if (!this.IsGlobal) {
  22888. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22889. }
  22890. return result;
  22891. };
  22892. // Dispose
  22893. /**
  22894. * Disposes the Submesh.
  22895. * Returns nothing.
  22896. */
  22897. SubMesh.prototype.dispose = function () {
  22898. if (this._linesIndexBuffer) {
  22899. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22900. this._linesIndexBuffer = null;
  22901. }
  22902. // Remove from mesh
  22903. var index = this._mesh.subMeshes.indexOf(this);
  22904. this._mesh.subMeshes.splice(index, 1);
  22905. };
  22906. // Statics
  22907. /**
  22908. * Creates a new Submesh from the passed parameters :
  22909. * - materialIndex (integer) : the index of the main mesh material.
  22910. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22911. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22912. * - mesh (Mesh) : the main mesh to create the submesh from.
  22913. * - renderingMesh (optional Mesh) : rendering mesh.
  22914. */
  22915. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22916. var minVertexIndex = Number.MAX_VALUE;
  22917. var maxVertexIndex = -Number.MAX_VALUE;
  22918. renderingMesh = renderingMesh || mesh;
  22919. var indices = renderingMesh.getIndices();
  22920. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22921. var vertexIndex = indices[index];
  22922. if (vertexIndex < minVertexIndex)
  22923. minVertexIndex = vertexIndex;
  22924. if (vertexIndex > maxVertexIndex)
  22925. maxVertexIndex = vertexIndex;
  22926. }
  22927. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22928. };
  22929. return SubMesh;
  22930. }(BaseSubMesh));
  22931. BABYLON.SubMesh = SubMesh;
  22932. })(BABYLON || (BABYLON = {}));
  22933. //# sourceMappingURL=babylon.subMesh.js.map
  22934. var BABYLON;
  22935. (function (BABYLON) {
  22936. var EffectFallbacks = (function () {
  22937. function EffectFallbacks() {
  22938. this._defines = {};
  22939. this._currentRank = 32;
  22940. this._maxRank = -1;
  22941. }
  22942. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22943. if (!this._defines[rank]) {
  22944. if (rank < this._currentRank) {
  22945. this._currentRank = rank;
  22946. }
  22947. if (rank > this._maxRank) {
  22948. this._maxRank = rank;
  22949. }
  22950. this._defines[rank] = new Array();
  22951. }
  22952. this._defines[rank].push(define);
  22953. };
  22954. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22955. this._meshRank = rank;
  22956. this._mesh = mesh;
  22957. if (rank < this._currentRank) {
  22958. this._currentRank = rank;
  22959. }
  22960. if (rank > this._maxRank) {
  22961. this._maxRank = rank;
  22962. }
  22963. };
  22964. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22965. get: function () {
  22966. return this._currentRank <= this._maxRank;
  22967. },
  22968. enumerable: true,
  22969. configurable: true
  22970. });
  22971. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22972. // First we try to switch to CPU skinning
  22973. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22974. this._mesh.computeBonesUsingShaders = false;
  22975. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22976. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22977. var scene = this._mesh.getScene();
  22978. for (var index = 0; index < scene.meshes.length; index++) {
  22979. var otherMesh = scene.meshes[index];
  22980. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22981. otherMesh.computeBonesUsingShaders = false;
  22982. }
  22983. }
  22984. }
  22985. else {
  22986. var currentFallbacks = this._defines[this._currentRank];
  22987. if (currentFallbacks) {
  22988. for (var index = 0; index < currentFallbacks.length; index++) {
  22989. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22990. }
  22991. }
  22992. this._currentRank++;
  22993. }
  22994. return currentDefines;
  22995. };
  22996. return EffectFallbacks;
  22997. }());
  22998. BABYLON.EffectFallbacks = EffectFallbacks;
  22999. var EffectCreationOptions = (function () {
  23000. function EffectCreationOptions() {
  23001. }
  23002. return EffectCreationOptions;
  23003. }());
  23004. BABYLON.EffectCreationOptions = EffectCreationOptions;
  23005. var Effect = (function () {
  23006. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23007. var _this = this;
  23008. this.uniqueId = 0;
  23009. this.onCompileObservable = new BABYLON.Observable();
  23010. this.onErrorObservable = new BABYLON.Observable();
  23011. this.onBindObservable = new BABYLON.Observable();
  23012. this._uniformBuffersNames = {};
  23013. this._isReady = false;
  23014. this._compilationError = "";
  23015. this._valueCache = {};
  23016. this.name = baseName;
  23017. if (attributesNamesOrOptions.attributes) {
  23018. var options = attributesNamesOrOptions;
  23019. this._engine = uniformsNamesOrEngine;
  23020. this._attributesNames = options.attributes;
  23021. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  23022. this._samplers = options.samplers;
  23023. this.defines = options.defines;
  23024. this.onError = options.onError;
  23025. this.onCompiled = options.onCompiled;
  23026. this._fallbacks = options.fallbacks;
  23027. this._indexParameters = options.indexParameters;
  23028. if (options.uniformBuffersNames) {
  23029. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  23030. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  23031. }
  23032. }
  23033. }
  23034. else {
  23035. this._engine = engine;
  23036. this.defines = defines;
  23037. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  23038. this._samplers = samplers;
  23039. this._attributesNames = attributesNamesOrOptions;
  23040. this.onError = onError;
  23041. this.onCompiled = onCompiled;
  23042. this._indexParameters = indexParameters;
  23043. this._fallbacks = fallbacks;
  23044. }
  23045. this.uniqueId = Effect._uniqueIdSeed++;
  23046. var vertexSource;
  23047. var fragmentSource;
  23048. if (baseName.vertexElement) {
  23049. vertexSource = document.getElementById(baseName.vertexElement);
  23050. if (!vertexSource) {
  23051. vertexSource = baseName.vertexElement;
  23052. }
  23053. }
  23054. else {
  23055. vertexSource = baseName.vertex || baseName;
  23056. }
  23057. if (baseName.fragmentElement) {
  23058. fragmentSource = document.getElementById(baseName.fragmentElement);
  23059. if (!fragmentSource) {
  23060. fragmentSource = baseName.fragmentElement;
  23061. }
  23062. }
  23063. else {
  23064. fragmentSource = baseName.fragment || baseName;
  23065. }
  23066. this._loadVertexShader(vertexSource, function (vertexCode) {
  23067. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23068. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  23069. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23070. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23071. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  23072. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  23073. });
  23074. });
  23075. });
  23076. });
  23077. });
  23078. });
  23079. }
  23080. Object.defineProperty(Effect.prototype, "key", {
  23081. get: function () {
  23082. return this._key;
  23083. },
  23084. enumerable: true,
  23085. configurable: true
  23086. });
  23087. // Properties
  23088. Effect.prototype.isReady = function () {
  23089. return this._isReady;
  23090. };
  23091. Effect.prototype.getEngine = function () {
  23092. return this._engine;
  23093. };
  23094. Effect.prototype.getProgram = function () {
  23095. return this._program;
  23096. };
  23097. Effect.prototype.getAttributesNames = function () {
  23098. return this._attributesNames;
  23099. };
  23100. Effect.prototype.getAttributeLocation = function (index) {
  23101. return this._attributes[index];
  23102. };
  23103. Effect.prototype.getAttributeLocationByName = function (name) {
  23104. var index = this._attributesNames.indexOf(name);
  23105. return this._attributes[index];
  23106. };
  23107. Effect.prototype.getAttributesCount = function () {
  23108. return this._attributes.length;
  23109. };
  23110. Effect.prototype.getUniformIndex = function (uniformName) {
  23111. return this._uniformsNames.indexOf(uniformName);
  23112. };
  23113. Effect.prototype.getUniform = function (uniformName) {
  23114. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23115. };
  23116. Effect.prototype.getSamplers = function () {
  23117. return this._samplers;
  23118. };
  23119. Effect.prototype.getCompilationError = function () {
  23120. return this._compilationError;
  23121. };
  23122. Effect.prototype.getVertexShaderSource = function () {
  23123. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  23124. };
  23125. Effect.prototype.getFragmentShaderSource = function () {
  23126. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  23127. };
  23128. // Methods
  23129. Effect.prototype.executeWhenCompiled = function (func) {
  23130. var _this = this;
  23131. if (this.isReady()) {
  23132. func(this);
  23133. return;
  23134. }
  23135. var observer = this.onCompileObservable.add(function (effect) {
  23136. _this.onCompileObservable.remove(observer);
  23137. func(effect);
  23138. });
  23139. };
  23140. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23141. // DOM element ?
  23142. if (vertex instanceof HTMLElement) {
  23143. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23144. callback(vertexCode);
  23145. return;
  23146. }
  23147. // Base64 encoded ?
  23148. if (vertex.substr(0, 7) === "base64:") {
  23149. var vertexBinary = window.atob(vertex.substr(7));
  23150. callback(vertexBinary);
  23151. return;
  23152. }
  23153. // Is in local store ?
  23154. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23155. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23156. return;
  23157. }
  23158. var vertexShaderUrl;
  23159. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23160. vertexShaderUrl = vertex;
  23161. }
  23162. else {
  23163. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23164. }
  23165. // Vertex shader
  23166. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23167. };
  23168. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23169. // DOM element ?
  23170. if (fragment instanceof HTMLElement) {
  23171. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23172. callback(fragmentCode);
  23173. return;
  23174. }
  23175. // Base64 encoded ?
  23176. if (fragment.substr(0, 7) === "base64:") {
  23177. var fragmentBinary = window.atob(fragment.substr(7));
  23178. callback(fragmentBinary);
  23179. return;
  23180. }
  23181. // Is in local store ?
  23182. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23183. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23184. return;
  23185. }
  23186. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23187. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23188. return;
  23189. }
  23190. var fragmentShaderUrl;
  23191. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23192. fragmentShaderUrl = fragment;
  23193. }
  23194. else {
  23195. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23196. }
  23197. // Fragment shader
  23198. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23199. };
  23200. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  23201. // Rebuild shaders source code
  23202. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  23203. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  23204. vertexCode = prefix + vertexCode;
  23205. fragmentCode = prefix + fragmentCode;
  23206. // Number lines of shaders source code
  23207. var i = 2;
  23208. var regex = /\n/gm;
  23209. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23210. i = 2;
  23211. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23212. // Dump shaders name and formatted source code
  23213. if (this.name.vertexElement) {
  23214. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  23215. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  23216. }
  23217. else if (this.name.vertex) {
  23218. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  23219. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  23220. }
  23221. else {
  23222. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  23223. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  23224. }
  23225. };
  23226. ;
  23227. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  23228. var preparedSourceCode = this._processPrecision(sourceCode);
  23229. if (this._engine.webGLVersion == 1) {
  23230. callback(preparedSourceCode);
  23231. return;
  23232. }
  23233. // Already converted
  23234. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  23235. callback(preparedSourceCode.replace("#version 300 es", ""));
  23236. return;
  23237. }
  23238. // Remove extensions
  23239. // #extension GL_OES_standard_derivatives : enable
  23240. // #extension GL_EXT_shader_texture_lod : enable
  23241. // #extension GL_EXT_frag_depth : enable
  23242. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  23243. var result = preparedSourceCode.replace(regex, "");
  23244. // Migrate to GLSL v300
  23245. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  23246. result = result.replace(/attribute[ \t]/g, "in ");
  23247. result = result.replace(/[ \t]attribute/g, " in");
  23248. if (isFragment) {
  23249. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  23250. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  23251. result = result.replace(/texture2D\(/g, "texture(");
  23252. result = result.replace(/textureCube\(/g, "texture(");
  23253. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  23254. result = result.replace(/gl_FragColor/g, "glFragColor");
  23255. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  23256. }
  23257. callback(result);
  23258. };
  23259. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23260. var _this = this;
  23261. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23262. var match = regex.exec(sourceCode);
  23263. var returnValue = new String(sourceCode);
  23264. while (match != null) {
  23265. var includeFile = match[1];
  23266. // Uniform declaration
  23267. if (includeFile.indexOf("__decl__") !== -1) {
  23268. includeFile = includeFile.replace(/__decl__/, "");
  23269. if (this._engine.webGLVersion != 1) {
  23270. includeFile = includeFile.replace(/Vertex/, "Ubo");
  23271. includeFile = includeFile.replace(/Fragment/, "Ubo");
  23272. }
  23273. includeFile = includeFile + "Declaration";
  23274. }
  23275. if (Effect.IncludesShadersStore[includeFile]) {
  23276. // Substitution
  23277. var includeContent = Effect.IncludesShadersStore[includeFile];
  23278. if (match[2]) {
  23279. var splits = match[3].split(",");
  23280. for (var index = 0; index < splits.length; index += 2) {
  23281. var source = new RegExp(splits[index], "g");
  23282. var dest = splits[index + 1];
  23283. includeContent = includeContent.replace(source, dest);
  23284. }
  23285. }
  23286. if (match[4]) {
  23287. var indexString = match[5];
  23288. if (indexString.indexOf("..") !== -1) {
  23289. var indexSplits = indexString.split("..");
  23290. var minIndex = parseInt(indexSplits[0]);
  23291. var maxIndex = parseInt(indexSplits[1]);
  23292. var sourceIncludeContent = includeContent.slice(0);
  23293. includeContent = "";
  23294. if (isNaN(maxIndex)) {
  23295. maxIndex = this._indexParameters[indexSplits[1]];
  23296. }
  23297. for (var i = minIndex; i < maxIndex; i++) {
  23298. if (this._engine.webGLVersion === 1) {
  23299. // Ubo replacement
  23300. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23301. return p1 + "{X}";
  23302. });
  23303. }
  23304. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23305. }
  23306. }
  23307. else {
  23308. if (this._engine.webGLVersion === 1) {
  23309. // Ubo replacement
  23310. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23311. return p1 + "{X}";
  23312. });
  23313. }
  23314. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23315. }
  23316. }
  23317. // Replace
  23318. returnValue = returnValue.replace(match[0], includeContent);
  23319. }
  23320. else {
  23321. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23322. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23323. Effect.IncludesShadersStore[includeFile] = fileContent;
  23324. _this._processIncludes(returnValue, callback);
  23325. });
  23326. return;
  23327. }
  23328. match = regex.exec(sourceCode);
  23329. }
  23330. callback(returnValue);
  23331. };
  23332. Effect.prototype._processPrecision = function (source) {
  23333. if (source.indexOf("precision highp float") === -1) {
  23334. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23335. source = "precision mediump float;\n" + source;
  23336. }
  23337. else {
  23338. source = "precision highp float;\n" + source;
  23339. }
  23340. }
  23341. else {
  23342. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23343. source = source.replace("precision highp float", "precision mediump float");
  23344. }
  23345. }
  23346. return source;
  23347. };
  23348. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23349. try {
  23350. var engine = this._engine;
  23351. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23352. if (engine.webGLVersion > 1) {
  23353. for (var name in this._uniformBuffersNames) {
  23354. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  23355. }
  23356. }
  23357. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23358. this._attributes = engine.getAttributes(this._program, attributesNames);
  23359. var index;
  23360. for (index = 0; index < this._samplers.length; index++) {
  23361. var sampler = this.getUniform(this._samplers[index]);
  23362. if (sampler == null) {
  23363. this._samplers.splice(index, 1);
  23364. index--;
  23365. }
  23366. }
  23367. engine.bindSamplers(this);
  23368. this._compilationError = "";
  23369. this._isReady = true;
  23370. if (this.onCompiled) {
  23371. this.onCompiled(this);
  23372. }
  23373. this.onCompileObservable.notifyObservers(this);
  23374. }
  23375. catch (e) {
  23376. this._compilationError = e.message;
  23377. // Let's go through fallbacks then
  23378. BABYLON.Tools.Error("Unable to compile effect:");
  23379. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23380. return " " + uniform;
  23381. }));
  23382. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23383. return " " + attribute;
  23384. }));
  23385. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23386. BABYLON.Tools.Error("Error: " + this._compilationError);
  23387. if (fallbacks && fallbacks.isMoreFallbacks) {
  23388. BABYLON.Tools.Error("Trying next fallback.");
  23389. defines = fallbacks.reduce(defines);
  23390. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23391. }
  23392. else {
  23393. if (this.onError) {
  23394. this.onError(this, this._compilationError);
  23395. }
  23396. this.onErrorObservable.notifyObservers(this);
  23397. }
  23398. }
  23399. };
  23400. Object.defineProperty(Effect.prototype, "isSupported", {
  23401. get: function () {
  23402. return this._compilationError === "";
  23403. },
  23404. enumerable: true,
  23405. configurable: true
  23406. });
  23407. Effect.prototype._bindTexture = function (channel, texture) {
  23408. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23409. };
  23410. Effect.prototype.setTexture = function (channel, texture) {
  23411. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23412. };
  23413. Effect.prototype.setTextureArray = function (channel, textures) {
  23414. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23415. var initialPos = this._samplers.indexOf(channel);
  23416. for (var index = 1; index < textures.length; index++) {
  23417. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23418. }
  23419. }
  23420. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23421. };
  23422. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23423. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23424. };
  23425. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23426. var cache = this._valueCache[uniformName];
  23427. var flag = matrix.updateFlag;
  23428. if (cache !== undefined && cache === flag) {
  23429. return false;
  23430. }
  23431. this._valueCache[uniformName] = flag;
  23432. return true;
  23433. };
  23434. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23435. var cache = this._valueCache[uniformName];
  23436. if (!cache) {
  23437. cache = [x, y];
  23438. this._valueCache[uniformName] = cache;
  23439. return true;
  23440. }
  23441. var changed = false;
  23442. if (cache[0] !== x) {
  23443. cache[0] = x;
  23444. changed = true;
  23445. }
  23446. if (cache[1] !== y) {
  23447. cache[1] = y;
  23448. changed = true;
  23449. }
  23450. return changed;
  23451. };
  23452. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23453. var cache = this._valueCache[uniformName];
  23454. if (!cache) {
  23455. cache = [x, y, z];
  23456. this._valueCache[uniformName] = cache;
  23457. return true;
  23458. }
  23459. var changed = false;
  23460. if (cache[0] !== x) {
  23461. cache[0] = x;
  23462. changed = true;
  23463. }
  23464. if (cache[1] !== y) {
  23465. cache[1] = y;
  23466. changed = true;
  23467. }
  23468. if (cache[2] !== z) {
  23469. cache[2] = z;
  23470. changed = true;
  23471. }
  23472. return changed;
  23473. };
  23474. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23475. var cache = this._valueCache[uniformName];
  23476. if (!cache) {
  23477. cache = [x, y, z, w];
  23478. this._valueCache[uniformName] = cache;
  23479. return true;
  23480. }
  23481. var changed = false;
  23482. if (cache[0] !== x) {
  23483. cache[0] = x;
  23484. changed = true;
  23485. }
  23486. if (cache[1] !== y) {
  23487. cache[1] = y;
  23488. changed = true;
  23489. }
  23490. if (cache[2] !== z) {
  23491. cache[2] = z;
  23492. changed = true;
  23493. }
  23494. if (cache[3] !== w) {
  23495. cache[3] = w;
  23496. changed = true;
  23497. }
  23498. return changed;
  23499. };
  23500. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23501. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23502. return;
  23503. }
  23504. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23505. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23506. };
  23507. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23508. this._engine.bindUniformBlock(this._program, blockName, index);
  23509. };
  23510. Effect.prototype.setIntArray = function (uniformName, array) {
  23511. this._valueCache[uniformName] = null;
  23512. this._engine.setIntArray(this.getUniform(uniformName), array);
  23513. return this;
  23514. };
  23515. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23516. this._valueCache[uniformName] = null;
  23517. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23518. return this;
  23519. };
  23520. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23521. this._valueCache[uniformName] = null;
  23522. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23523. return this;
  23524. };
  23525. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23526. this._valueCache[uniformName] = null;
  23527. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23528. return this;
  23529. };
  23530. Effect.prototype.setFloatArray = function (uniformName, array) {
  23531. this._valueCache[uniformName] = null;
  23532. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23533. return this;
  23534. };
  23535. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23536. this._valueCache[uniformName] = null;
  23537. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23538. return this;
  23539. };
  23540. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23541. this._valueCache[uniformName] = null;
  23542. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23543. return this;
  23544. };
  23545. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23546. this._valueCache[uniformName] = null;
  23547. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23548. return this;
  23549. };
  23550. Effect.prototype.setArray = function (uniformName, array) {
  23551. this._valueCache[uniformName] = null;
  23552. this._engine.setArray(this.getUniform(uniformName), array);
  23553. return this;
  23554. };
  23555. Effect.prototype.setArray2 = function (uniformName, array) {
  23556. this._valueCache[uniformName] = null;
  23557. this._engine.setArray2(this.getUniform(uniformName), array);
  23558. return this;
  23559. };
  23560. Effect.prototype.setArray3 = function (uniformName, array) {
  23561. this._valueCache[uniformName] = null;
  23562. this._engine.setArray3(this.getUniform(uniformName), array);
  23563. return this;
  23564. };
  23565. Effect.prototype.setArray4 = function (uniformName, array) {
  23566. this._valueCache[uniformName] = null;
  23567. this._engine.setArray4(this.getUniform(uniformName), array);
  23568. return this;
  23569. };
  23570. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23571. if (!matrices) {
  23572. return;
  23573. }
  23574. this._valueCache[uniformName] = null;
  23575. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23576. return this;
  23577. };
  23578. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23579. if (this._cacheMatrix(uniformName, matrix)) {
  23580. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23581. }
  23582. return this;
  23583. };
  23584. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23585. this._valueCache[uniformName] = null;
  23586. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23587. return this;
  23588. };
  23589. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23590. this._valueCache[uniformName] = null;
  23591. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23592. return this;
  23593. };
  23594. Effect.prototype.setFloat = function (uniformName, value) {
  23595. var cache = this._valueCache[uniformName];
  23596. if (cache !== undefined && cache === value)
  23597. return this;
  23598. this._valueCache[uniformName] = value;
  23599. this._engine.setFloat(this.getUniform(uniformName), value);
  23600. return this;
  23601. };
  23602. Effect.prototype.setBool = function (uniformName, bool) {
  23603. var cache = this._valueCache[uniformName];
  23604. if (cache !== undefined && cache === bool)
  23605. return this;
  23606. this._valueCache[uniformName] = bool;
  23607. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23608. return this;
  23609. };
  23610. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23611. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23612. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23613. }
  23614. return this;
  23615. };
  23616. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23617. if (this._cacheFloat2(uniformName, x, y)) {
  23618. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23619. }
  23620. return this;
  23621. };
  23622. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23623. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23624. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23625. }
  23626. return this;
  23627. };
  23628. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23629. if (this._cacheFloat3(uniformName, x, y, z)) {
  23630. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23631. }
  23632. return this;
  23633. };
  23634. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23635. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23636. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23637. }
  23638. return this;
  23639. };
  23640. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23641. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23642. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23643. }
  23644. return this;
  23645. };
  23646. Effect.prototype.setColor3 = function (uniformName, color3) {
  23647. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23648. this._engine.setColor3(this.getUniform(uniformName), color3);
  23649. }
  23650. return this;
  23651. };
  23652. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23653. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23654. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23655. }
  23656. return this;
  23657. };
  23658. Effect.prototype._recombineShader = function (node) {
  23659. if (node.define) {
  23660. if (node.condition) {
  23661. var defineIndex = this.defines.indexOf("#define " + node.define);
  23662. if (defineIndex === -1) {
  23663. return null;
  23664. }
  23665. var nextComma = this.defines.indexOf("\n", defineIndex);
  23666. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23667. var condition = defineValue + node.condition;
  23668. if (!eval(condition)) {
  23669. return null;
  23670. }
  23671. }
  23672. else if (node.ndef) {
  23673. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23674. return null;
  23675. }
  23676. }
  23677. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23678. return null;
  23679. }
  23680. }
  23681. var result = "";
  23682. for (var index = 0; index < node.children.length; index++) {
  23683. var line = node.children[index];
  23684. if (line.children) {
  23685. var combined = this._recombineShader(line);
  23686. if (combined !== null) {
  23687. result += combined + "\r\n";
  23688. }
  23689. continue;
  23690. }
  23691. if (line.length > 0) {
  23692. result += line + "\r\n";
  23693. }
  23694. }
  23695. return result;
  23696. };
  23697. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23698. var root = {
  23699. children: []
  23700. };
  23701. var currentNode = root;
  23702. var lines = shaderString.split("\n");
  23703. for (var index = 0; index < lines.length; index++) {
  23704. var line = lines[index].trim();
  23705. // #ifdef
  23706. var pos = line.indexOf("#ifdef ");
  23707. if (pos !== -1) {
  23708. var define = line.substr(pos + 7);
  23709. var newNode = {
  23710. condition: null,
  23711. ndef: false,
  23712. define: define,
  23713. children: [],
  23714. parent: currentNode
  23715. };
  23716. currentNode.children.push(newNode);
  23717. currentNode = newNode;
  23718. continue;
  23719. }
  23720. // #ifndef
  23721. var pos = line.indexOf("#ifndef ");
  23722. if (pos !== -1) {
  23723. var define = line.substr(pos + 8);
  23724. newNode = {
  23725. condition: null,
  23726. define: define,
  23727. ndef: true,
  23728. children: [],
  23729. parent: currentNode
  23730. };
  23731. currentNode.children.push(newNode);
  23732. currentNode = newNode;
  23733. continue;
  23734. }
  23735. // #if
  23736. var pos = line.indexOf("#if ");
  23737. if (pos !== -1) {
  23738. var define = line.substr(pos + 4).trim();
  23739. var conditionPos = define.indexOf(" ");
  23740. newNode = {
  23741. condition: define.substr(conditionPos + 1),
  23742. define: define.substr(0, conditionPos),
  23743. ndef: false,
  23744. children: [],
  23745. parent: currentNode
  23746. };
  23747. currentNode.children.push(newNode);
  23748. currentNode = newNode;
  23749. continue;
  23750. }
  23751. // #endif
  23752. pos = line.indexOf("#endif");
  23753. if (pos !== -1) {
  23754. currentNode = currentNode.parent;
  23755. continue;
  23756. }
  23757. currentNode.children.push(line);
  23758. }
  23759. // Recombine
  23760. return this._recombineShader(root);
  23761. };
  23762. return Effect;
  23763. }());
  23764. Effect._uniqueIdSeed = 0;
  23765. Effect._baseCache = {};
  23766. // Statics
  23767. Effect.ShadersStore = {};
  23768. Effect.IncludesShadersStore = {};
  23769. BABYLON.Effect = Effect;
  23770. })(BABYLON || (BABYLON = {}));
  23771. //# sourceMappingURL=babylon.effect.js.map
  23772. var BABYLON;
  23773. (function (BABYLON) {
  23774. var MaterialHelper = (function () {
  23775. function MaterialHelper() {
  23776. }
  23777. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  23778. defines._needUVs = true;
  23779. defines[key] = true;
  23780. if (texture.getTextureMatrix().isIdentity(true)) {
  23781. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  23782. if (texture.coordinatesIndex === 0) {
  23783. defines["MAINUV1"] = true;
  23784. }
  23785. else {
  23786. defines["MAINUV2"] = true;
  23787. }
  23788. }
  23789. else {
  23790. defines[key + "DIRECTUV"] = 0;
  23791. }
  23792. };
  23793. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  23794. var matrix = texture.getTextureMatrix();
  23795. if (!matrix.isIdentity(true)) {
  23796. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  23797. }
  23798. };
  23799. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23800. if (defines._areMiscDirty) {
  23801. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23802. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23803. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23804. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23805. }
  23806. };
  23807. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23808. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23809. var changed = false;
  23810. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23811. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23812. changed = true;
  23813. }
  23814. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23815. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23816. changed = true;
  23817. }
  23818. if (defines["INSTANCES"] !== useInstances) {
  23819. defines["INSTANCES"] = useInstances;
  23820. changed = true;
  23821. }
  23822. if (changed) {
  23823. defines.markAsUnprocessed();
  23824. }
  23825. };
  23826. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23827. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23828. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23829. return false;
  23830. }
  23831. defines._normals = defines._needNormals;
  23832. defines._uvs = defines._needUVs;
  23833. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23834. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23835. defines["TANGENT"] = true;
  23836. }
  23837. if (defines._needUVs) {
  23838. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23839. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23840. }
  23841. else {
  23842. defines["UV1"] = false;
  23843. defines["UV2"] = false;
  23844. }
  23845. if (useVertexColor) {
  23846. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23847. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23848. }
  23849. if (useBones) {
  23850. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23851. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23852. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23853. }
  23854. else {
  23855. defines["NUM_BONE_INFLUENCERS"] = 0;
  23856. defines["BonesPerMesh"] = 0;
  23857. }
  23858. }
  23859. if (useMorphTargets) {
  23860. if (mesh.morphTargetManager) {
  23861. var manager = mesh.morphTargetManager;
  23862. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23863. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23864. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23865. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23866. }
  23867. else {
  23868. defines["MORPHTARGETS_TANGENT"] = false;
  23869. defines["MORPHTARGETS_NORMAL"] = false;
  23870. defines["MORPHTARGETS"] = false;
  23871. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23872. }
  23873. }
  23874. return true;
  23875. };
  23876. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23877. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23878. if (disableLighting === void 0) { disableLighting = false; }
  23879. if (!defines._areLightsDirty) {
  23880. return defines._needNormals;
  23881. }
  23882. var lightIndex = 0;
  23883. var needNormals = false;
  23884. var needRebuild = false;
  23885. var lightmapMode = false;
  23886. var shadowEnabled = false;
  23887. var specularEnabled = false;
  23888. if (scene.lightsEnabled && !disableLighting) {
  23889. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23890. var light = _a[_i];
  23891. needNormals = true;
  23892. if (defines["LIGHT" + lightIndex] === undefined) {
  23893. needRebuild = true;
  23894. }
  23895. defines["LIGHT" + lightIndex] = true;
  23896. defines["SPOTLIGHT" + lightIndex] = false;
  23897. defines["HEMILIGHT" + lightIndex] = false;
  23898. defines["POINTLIGHT" + lightIndex] = false;
  23899. defines["DIRLIGHT" + lightIndex] = false;
  23900. var type;
  23901. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23902. type = "SPOTLIGHT" + lightIndex;
  23903. }
  23904. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23905. type = "HEMILIGHT" + lightIndex;
  23906. }
  23907. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23908. type = "POINTLIGHT" + lightIndex;
  23909. }
  23910. else {
  23911. type = "DIRLIGHT" + lightIndex;
  23912. }
  23913. defines[type] = true;
  23914. // Specular
  23915. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23916. specularEnabled = true;
  23917. }
  23918. // Shadows
  23919. defines["SHADOW" + lightIndex] = false;
  23920. defines["SHADOWPCF" + lightIndex] = false;
  23921. defines["SHADOWESM" + lightIndex] = false;
  23922. defines["SHADOWCUBE" + lightIndex] = false;
  23923. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23924. var shadowGenerator = light.getShadowGenerator();
  23925. if (shadowGenerator) {
  23926. shadowEnabled = true;
  23927. shadowGenerator.prepareDefines(defines, lightIndex);
  23928. }
  23929. }
  23930. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23931. lightmapMode = true;
  23932. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23933. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23934. }
  23935. else {
  23936. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23937. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23938. }
  23939. lightIndex++;
  23940. if (lightIndex === maxSimultaneousLights)
  23941. break;
  23942. }
  23943. }
  23944. defines["SPECULARTERM"] = specularEnabled;
  23945. defines["SHADOWS"] = shadowEnabled;
  23946. // Resetting all other lights if any
  23947. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23948. if (defines["LIGHT" + index] !== undefined) {
  23949. defines["LIGHT" + index] = false;
  23950. defines["HEMILIGHT" + lightIndex] = false;
  23951. defines["POINTLIGHT" + lightIndex] = false;
  23952. defines["DIRLIGHT" + lightIndex] = false;
  23953. defines["SPOTLIGHT" + lightIndex] = false;
  23954. defines["SHADOW" + lightIndex] = false;
  23955. }
  23956. }
  23957. var caps = scene.getEngine().getCaps();
  23958. if (defines["SHADOWFLOAT"] === undefined) {
  23959. needRebuild = true;
  23960. }
  23961. defines["SHADOWFLOAT"] = shadowEnabled &&
  23962. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23963. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23964. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23965. if (needRebuild) {
  23966. defines.rebuild();
  23967. }
  23968. return needNormals;
  23969. };
  23970. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23971. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23972. var uniformsList, uniformBuffersList, samplersList, defines;
  23973. if (uniformsListOrOptions.uniformsNames) {
  23974. var options = uniformsListOrOptions;
  23975. uniformsList = options.uniformsNames;
  23976. uniformBuffersList = options.uniformBuffersNames;
  23977. samplersList = options.samplers;
  23978. defines = options.defines;
  23979. maxSimultaneousLights = options.maxSimultaneousLights;
  23980. }
  23981. else {
  23982. uniformsList = uniformsListOrOptions;
  23983. }
  23984. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23985. if (!defines["LIGHT" + lightIndex]) {
  23986. break;
  23987. }
  23988. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  23989. if (uniformBuffersList) {
  23990. uniformBuffersList.push("Light" + lightIndex);
  23991. }
  23992. samplersList.push("shadowSampler" + lightIndex);
  23993. }
  23994. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23995. uniformsList.push("morphTargetInfluences");
  23996. }
  23997. };
  23998. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23999. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24000. if (!defines["SHADOWS"]) {
  24001. return;
  24002. }
  24003. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24004. if (!defines["LIGHT" + lightIndex]) {
  24005. break;
  24006. }
  24007. if (lightIndex > 0) {
  24008. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24009. }
  24010. if (defines["SHADOW" + lightIndex]) {
  24011. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24012. }
  24013. if (defines["SHADOWPCF" + lightIndex]) {
  24014. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24015. }
  24016. if (defines["SHADOWESM" + lightIndex]) {
  24017. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24018. }
  24019. }
  24020. };
  24021. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24022. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24023. if (influencers > 0) {
  24024. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24025. var manager = mesh.morphTargetManager;
  24026. var normal = manager.supportsNormals && defines["NORMAL"];
  24027. var tangent = manager.supportsTangents && defines["TANGENT"];
  24028. for (var index = 0; index < influencers; index++) {
  24029. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24030. if (normal) {
  24031. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24032. }
  24033. if (tangent) {
  24034. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24035. }
  24036. if (attribs.length > maxAttributesCount) {
  24037. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24038. }
  24039. }
  24040. }
  24041. };
  24042. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24043. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24044. fallbacks.addCPUSkinningFallback(0, mesh);
  24045. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24046. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24047. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24048. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24049. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24050. }
  24051. }
  24052. };
  24053. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24054. if (defines["INSTANCES"]) {
  24055. attribs.push("world0");
  24056. attribs.push("world1");
  24057. attribs.push("world2");
  24058. attribs.push("world3");
  24059. }
  24060. };
  24061. // Bindings
  24062. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24063. if (light.shadowEnabled && mesh.receiveShadows) {
  24064. var shadowGenerator = light.getShadowGenerator();
  24065. if (shadowGenerator) {
  24066. shadowGenerator.bindShadowLight(lightIndex, effect);
  24067. }
  24068. }
  24069. };
  24070. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24071. light.transferToEffect(effect, lightIndex + "");
  24072. };
  24073. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  24074. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24075. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  24076. var lightIndex = 0;
  24077. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24078. var light = _a[_i];
  24079. var scaledIntensity = light.getScaledIntensity();
  24080. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  24081. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24082. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  24083. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  24084. if (defines["SPECULARTERM"]) {
  24085. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  24086. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  24087. }
  24088. // Shadows
  24089. if (scene.shadowsEnabled) {
  24090. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  24091. }
  24092. light._uniformBuffer.update();
  24093. lightIndex++;
  24094. if (lightIndex === maxSimultaneousLights)
  24095. break;
  24096. }
  24097. };
  24098. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24099. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24100. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24101. effect.setColor3("vFogColor", scene.fogColor);
  24102. }
  24103. };
  24104. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24105. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24106. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24107. if (matrices) {
  24108. effect.setMatrices("mBones", matrices);
  24109. }
  24110. }
  24111. };
  24112. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  24113. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  24114. return;
  24115. }
  24116. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  24117. };
  24118. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24119. if (defines["LOGARITHMICDEPTH"]) {
  24120. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24121. }
  24122. };
  24123. MaterialHelper.BindClipPlane = function (effect, scene) {
  24124. if (scene.clipPlane) {
  24125. var clipPlane = scene.clipPlane;
  24126. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24127. }
  24128. };
  24129. return MaterialHelper;
  24130. }());
  24131. BABYLON.MaterialHelper = MaterialHelper;
  24132. })(BABYLON || (BABYLON = {}));
  24133. //# sourceMappingURL=babylon.materialHelper.js.map
  24134. var BABYLON;
  24135. (function (BABYLON) {
  24136. var MaterialDefines = (function () {
  24137. function MaterialDefines() {
  24138. this._isDirty = true;
  24139. this._areLightsDirty = true;
  24140. this._areAttributesDirty = true;
  24141. this._areTexturesDirty = true;
  24142. this._areFresnelDirty = true;
  24143. this._areMiscDirty = true;
  24144. this._areImageProcessingDirty = true;
  24145. this._normals = false;
  24146. this._uvs = false;
  24147. this._needNormals = false;
  24148. this._needUVs = false;
  24149. }
  24150. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  24151. get: function () {
  24152. return this._isDirty;
  24153. },
  24154. enumerable: true,
  24155. configurable: true
  24156. });
  24157. MaterialDefines.prototype.markAsProcessed = function () {
  24158. this._isDirty = false;
  24159. this._areAttributesDirty = false;
  24160. this._areTexturesDirty = false;
  24161. this._areFresnelDirty = false;
  24162. this._areLightsDirty = false;
  24163. this._areMiscDirty = false;
  24164. this._areImageProcessingDirty = false;
  24165. };
  24166. MaterialDefines.prototype.markAsUnprocessed = function () {
  24167. this._isDirty = true;
  24168. };
  24169. MaterialDefines.prototype.markAllAsDirty = function () {
  24170. this._areTexturesDirty = true;
  24171. this._areAttributesDirty = true;
  24172. this._areLightsDirty = true;
  24173. this._areFresnelDirty = true;
  24174. this._areMiscDirty = true;
  24175. this._areImageProcessingDirty = true;
  24176. this._isDirty = true;
  24177. };
  24178. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  24179. this._areImageProcessingDirty = true;
  24180. this._isDirty = true;
  24181. };
  24182. MaterialDefines.prototype.markAsLightDirty = function () {
  24183. this._areLightsDirty = true;
  24184. this._isDirty = true;
  24185. };
  24186. MaterialDefines.prototype.markAsAttributesDirty = function () {
  24187. this._areAttributesDirty = true;
  24188. this._isDirty = true;
  24189. };
  24190. MaterialDefines.prototype.markAsTexturesDirty = function () {
  24191. this._areTexturesDirty = true;
  24192. this._isDirty = true;
  24193. };
  24194. MaterialDefines.prototype.markAsFresnelDirty = function () {
  24195. this._areFresnelDirty = true;
  24196. this._isDirty = true;
  24197. };
  24198. MaterialDefines.prototype.markAsMiscDirty = function () {
  24199. this._areMiscDirty = true;
  24200. this._isDirty = true;
  24201. };
  24202. MaterialDefines.prototype.rebuild = function () {
  24203. if (this._keys) {
  24204. delete this._keys;
  24205. }
  24206. this._keys = [];
  24207. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  24208. var key = _a[_i];
  24209. if (key[0] === "_") {
  24210. continue;
  24211. }
  24212. this._keys.push(key);
  24213. }
  24214. };
  24215. MaterialDefines.prototype.isEqual = function (other) {
  24216. if (this._keys.length !== other._keys.length) {
  24217. return false;
  24218. }
  24219. for (var index = 0; index < this._keys.length; index++) {
  24220. var prop = this._keys[index];
  24221. if (this[prop] !== other[prop]) {
  24222. return false;
  24223. }
  24224. }
  24225. return true;
  24226. };
  24227. MaterialDefines.prototype.cloneTo = function (other) {
  24228. if (this._keys.length !== other._keys.length) {
  24229. other._keys = this._keys.slice(0);
  24230. }
  24231. for (var index = 0; index < this._keys.length; index++) {
  24232. var prop = this._keys[index];
  24233. other[prop] = this[prop];
  24234. }
  24235. };
  24236. MaterialDefines.prototype.reset = function () {
  24237. for (var index = 0; index < this._keys.length; index++) {
  24238. var prop = this._keys[index];
  24239. if (typeof (this[prop]) === "number") {
  24240. this[prop] = 0;
  24241. }
  24242. else {
  24243. this[prop] = false;
  24244. }
  24245. }
  24246. };
  24247. MaterialDefines.prototype.toString = function () {
  24248. var result = "";
  24249. for (var index = 0; index < this._keys.length; index++) {
  24250. var prop = this._keys[index];
  24251. var value = this[prop];
  24252. if (typeof (value) === "number") {
  24253. result += "#define " + prop + " " + this[prop] + "\n";
  24254. }
  24255. else if (value) {
  24256. result += "#define " + prop + "\n";
  24257. }
  24258. }
  24259. return result;
  24260. };
  24261. return MaterialDefines;
  24262. }());
  24263. BABYLON.MaterialDefines = MaterialDefines;
  24264. var Material = (function () {
  24265. function Material(name, scene, doNotAdd) {
  24266. this.checkReadyOnEveryCall = false;
  24267. this.checkReadyOnlyOnce = false;
  24268. this.state = "";
  24269. this.alpha = 1.0;
  24270. this._backFaceCulling = true;
  24271. this.doNotSerialize = false;
  24272. this.storeEffectOnSubMeshes = false;
  24273. /**
  24274. * An event triggered when the material is disposed.
  24275. * @type {BABYLON.Observable}
  24276. */
  24277. this.onDisposeObservable = new BABYLON.Observable();
  24278. /**
  24279. * An event triggered when the material is bound.
  24280. * @type {BABYLON.Observable}
  24281. */
  24282. this.onBindObservable = new BABYLON.Observable();
  24283. /**
  24284. * An event triggered when the material is unbound.
  24285. * @type {BABYLON.Observable}
  24286. */
  24287. this.onUnBindObservable = new BABYLON.Observable();
  24288. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24289. this.disableDepthWrite = false;
  24290. this._fogEnabled = true;
  24291. this.pointSize = 1.0;
  24292. this.zOffset = 0;
  24293. this._wasPreviouslyReady = false;
  24294. this._fillMode = Material.TriangleFillMode;
  24295. this.name = name;
  24296. this.id = name;
  24297. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24298. if (this._scene.useRightHandedSystem) {
  24299. this.sideOrientation = Material.ClockWiseSideOrientation;
  24300. }
  24301. else {
  24302. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24303. }
  24304. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  24305. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  24306. if (!doNotAdd) {
  24307. this._scene.materials.push(this);
  24308. }
  24309. }
  24310. Object.defineProperty(Material, "TriangleFillMode", {
  24311. get: function () {
  24312. return Material._TriangleFillMode;
  24313. },
  24314. enumerable: true,
  24315. configurable: true
  24316. });
  24317. Object.defineProperty(Material, "WireFrameFillMode", {
  24318. get: function () {
  24319. return Material._WireFrameFillMode;
  24320. },
  24321. enumerable: true,
  24322. configurable: true
  24323. });
  24324. Object.defineProperty(Material, "PointFillMode", {
  24325. get: function () {
  24326. return Material._PointFillMode;
  24327. },
  24328. enumerable: true,
  24329. configurable: true
  24330. });
  24331. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24332. get: function () {
  24333. return Material._ClockWiseSideOrientation;
  24334. },
  24335. enumerable: true,
  24336. configurable: true
  24337. });
  24338. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24339. get: function () {
  24340. return Material._CounterClockWiseSideOrientation;
  24341. },
  24342. enumerable: true,
  24343. configurable: true
  24344. });
  24345. Object.defineProperty(Material, "TextureDirtyFlag", {
  24346. get: function () {
  24347. return Material._TextureDirtyFlag;
  24348. },
  24349. enumerable: true,
  24350. configurable: true
  24351. });
  24352. Object.defineProperty(Material, "LightDirtyFlag", {
  24353. get: function () {
  24354. return Material._LightDirtyFlag;
  24355. },
  24356. enumerable: true,
  24357. configurable: true
  24358. });
  24359. Object.defineProperty(Material, "FresnelDirtyFlag", {
  24360. get: function () {
  24361. return Material._FresnelDirtyFlag;
  24362. },
  24363. enumerable: true,
  24364. configurable: true
  24365. });
  24366. Object.defineProperty(Material, "AttributesDirtyFlag", {
  24367. get: function () {
  24368. return Material._AttributesDirtyFlag;
  24369. },
  24370. enumerable: true,
  24371. configurable: true
  24372. });
  24373. Object.defineProperty(Material, "MiscDirtyFlag", {
  24374. get: function () {
  24375. return Material._MiscDirtyFlag;
  24376. },
  24377. enumerable: true,
  24378. configurable: true
  24379. });
  24380. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24381. get: function () {
  24382. return this._backFaceCulling;
  24383. },
  24384. set: function (value) {
  24385. if (this._backFaceCulling === value) {
  24386. return;
  24387. }
  24388. this._backFaceCulling = value;
  24389. this.markAsDirty(Material.TextureDirtyFlag);
  24390. },
  24391. enumerable: true,
  24392. configurable: true
  24393. });
  24394. Object.defineProperty(Material.prototype, "onDispose", {
  24395. set: function (callback) {
  24396. if (this._onDisposeObserver) {
  24397. this.onDisposeObservable.remove(this._onDisposeObserver);
  24398. }
  24399. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. Object.defineProperty(Material.prototype, "onBind", {
  24405. set: function (callback) {
  24406. if (this._onBindObserver) {
  24407. this.onBindObservable.remove(this._onBindObserver);
  24408. }
  24409. this._onBindObserver = this.onBindObservable.add(callback);
  24410. },
  24411. enumerable: true,
  24412. configurable: true
  24413. });
  24414. Object.defineProperty(Material.prototype, "fogEnabled", {
  24415. get: function () {
  24416. return this._fogEnabled;
  24417. },
  24418. set: function (value) {
  24419. if (this._fogEnabled === value) {
  24420. return;
  24421. }
  24422. this._fogEnabled = value;
  24423. this.markAsDirty(Material.MiscDirtyFlag);
  24424. },
  24425. enumerable: true,
  24426. configurable: true
  24427. });
  24428. Object.defineProperty(Material.prototype, "wireframe", {
  24429. get: function () {
  24430. return this._fillMode === Material.WireFrameFillMode;
  24431. },
  24432. set: function (value) {
  24433. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24434. },
  24435. enumerable: true,
  24436. configurable: true
  24437. });
  24438. Object.defineProperty(Material.prototype, "pointsCloud", {
  24439. get: function () {
  24440. return this._fillMode === Material.PointFillMode;
  24441. },
  24442. set: function (value) {
  24443. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24444. },
  24445. enumerable: true,
  24446. configurable: true
  24447. });
  24448. Object.defineProperty(Material.prototype, "fillMode", {
  24449. get: function () {
  24450. return this._fillMode;
  24451. },
  24452. set: function (value) {
  24453. if (this._fillMode === value) {
  24454. return;
  24455. }
  24456. this._fillMode = value;
  24457. this.markAsDirty(Material.MiscDirtyFlag);
  24458. },
  24459. enumerable: true,
  24460. configurable: true
  24461. });
  24462. /**
  24463. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24464. * subclasses should override adding information pertainent to themselves
  24465. */
  24466. Material.prototype.toString = function (fullDetails) {
  24467. var ret = "Name: " + this.name;
  24468. if (fullDetails) {
  24469. }
  24470. return ret;
  24471. };
  24472. /**
  24473. * Child classes can use it to update shaders
  24474. */
  24475. Material.prototype.getClassName = function () {
  24476. return "Material";
  24477. };
  24478. Object.defineProperty(Material.prototype, "isFrozen", {
  24479. get: function () {
  24480. return this.checkReadyOnlyOnce;
  24481. },
  24482. enumerable: true,
  24483. configurable: true
  24484. });
  24485. Material.prototype.freeze = function () {
  24486. this.checkReadyOnlyOnce = true;
  24487. };
  24488. Material.prototype.unfreeze = function () {
  24489. this.checkReadyOnlyOnce = false;
  24490. };
  24491. Material.prototype.isReady = function (mesh, useInstances) {
  24492. return true;
  24493. };
  24494. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24495. return false;
  24496. };
  24497. Material.prototype.getEffect = function () {
  24498. return this._effect;
  24499. };
  24500. Material.prototype.getScene = function () {
  24501. return this._scene;
  24502. };
  24503. Material.prototype.needAlphaBlending = function () {
  24504. return (this.alpha < 1.0);
  24505. };
  24506. Material.prototype.needAlphaTesting = function () {
  24507. return false;
  24508. };
  24509. Material.prototype.getAlphaTestTexture = function () {
  24510. return null;
  24511. };
  24512. Material.prototype.markDirty = function () {
  24513. this._wasPreviouslyReady = false;
  24514. };
  24515. Material.prototype._preBind = function (effect) {
  24516. var engine = this._scene.getEngine();
  24517. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24518. engine.enableEffect(effect ? effect : this._effect);
  24519. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24520. };
  24521. Material.prototype.bind = function (world, mesh) {
  24522. };
  24523. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  24524. };
  24525. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24526. };
  24527. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  24528. sceneUbo.bindToEffect(effect, "Scene");
  24529. };
  24530. Material.prototype.bindView = function (effect) {
  24531. if (!this._useUBO) {
  24532. effect.setMatrix("view", this.getScene().getViewMatrix());
  24533. }
  24534. else {
  24535. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24536. }
  24537. };
  24538. Material.prototype.bindViewProjection = function (effect) {
  24539. if (!this._useUBO) {
  24540. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24541. }
  24542. else {
  24543. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24544. }
  24545. };
  24546. Material.prototype._afterBind = function (mesh) {
  24547. this._scene._cachedMaterial = this;
  24548. this.onBindObservable.notifyObservers(mesh);
  24549. if (this.disableDepthWrite) {
  24550. var engine = this._scene.getEngine();
  24551. this._cachedDepthWriteState = engine.getDepthWrite();
  24552. engine.setDepthWrite(false);
  24553. }
  24554. };
  24555. Material.prototype.unbind = function () {
  24556. this.onUnBindObservable.notifyObservers(this);
  24557. if (this.disableDepthWrite) {
  24558. var engine = this._scene.getEngine();
  24559. engine.setDepthWrite(this._cachedDepthWriteState);
  24560. }
  24561. };
  24562. Material.prototype.getActiveTextures = function () {
  24563. return [];
  24564. };
  24565. Material.prototype.hasTexture = function (texture) {
  24566. return false;
  24567. };
  24568. Material.prototype.clone = function (name) {
  24569. return null;
  24570. };
  24571. Material.prototype.getBindedMeshes = function () {
  24572. var result = new Array();
  24573. for (var index = 0; index < this._scene.meshes.length; index++) {
  24574. var mesh = this._scene.meshes[index];
  24575. if (mesh.material === this) {
  24576. result.push(mesh);
  24577. }
  24578. }
  24579. return result;
  24580. };
  24581. // Force shader compilation including textures ready check
  24582. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  24583. var _this = this;
  24584. var subMesh = new BABYLON.BaseSubMesh();
  24585. var scene = this.getScene();
  24586. var engine = scene.getEngine();
  24587. var beforeRenderCallback = function () {
  24588. if (subMesh._materialDefines) {
  24589. subMesh._materialDefines._renderId = -1;
  24590. }
  24591. var alphaTestState = engine.getAlphaTesting();
  24592. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  24593. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  24594. scene.unregisterBeforeRender(beforeRenderCallback);
  24595. if (onCompiled) {
  24596. onCompiled(_this);
  24597. }
  24598. }
  24599. engine.setAlphaTesting(alphaTestState);
  24600. };
  24601. scene.registerBeforeRender(beforeRenderCallback);
  24602. };
  24603. Material.prototype.markAsDirty = function (flag) {
  24604. if (flag & Material.TextureDirtyFlag) {
  24605. this._markAllSubMeshesAsTexturesDirty();
  24606. }
  24607. if (flag & Material.LightDirtyFlag) {
  24608. this._markAllSubMeshesAsLightsDirty();
  24609. }
  24610. if (flag & Material.FresnelDirtyFlag) {
  24611. this._markAllSubMeshesAsFresnelDirty();
  24612. }
  24613. if (flag & Material.AttributesDirtyFlag) {
  24614. this._markAllSubMeshesAsAttributesDirty();
  24615. }
  24616. if (flag & Material.MiscDirtyFlag) {
  24617. this._markAllSubMeshesAsMiscDirty();
  24618. }
  24619. this.getScene().resetCachedMaterial();
  24620. };
  24621. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  24622. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24623. var mesh = _a[_i];
  24624. if (!mesh.subMeshes) {
  24625. continue;
  24626. }
  24627. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24628. var subMesh = _c[_b];
  24629. if (subMesh.getMaterial() !== this) {
  24630. continue;
  24631. }
  24632. if (!subMesh._materialDefines) {
  24633. return;
  24634. }
  24635. func(subMesh._materialDefines);
  24636. }
  24637. }
  24638. };
  24639. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  24640. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  24641. };
  24642. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24643. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24644. };
  24645. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24646. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24647. };
  24648. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  24649. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24650. };
  24651. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24652. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24653. };
  24654. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  24655. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24656. };
  24657. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24658. // Animations
  24659. this.getScene().stopAnimation(this);
  24660. // Remove from scene
  24661. var index = this._scene.materials.indexOf(this);
  24662. if (index >= 0) {
  24663. this._scene.materials.splice(index, 1);
  24664. }
  24665. // Remove from meshes
  24666. for (index = 0; index < this._scene.meshes.length; index++) {
  24667. var mesh = this._scene.meshes[index];
  24668. if (mesh.material === this) {
  24669. mesh.material = null;
  24670. if (mesh.geometry) {
  24671. var geometry = mesh.geometry;
  24672. if (this.storeEffectOnSubMeshes) {
  24673. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24674. var subMesh = _a[_i];
  24675. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24676. }
  24677. }
  24678. else {
  24679. geometry._releaseVertexArrayObject(this._effect);
  24680. }
  24681. }
  24682. }
  24683. }
  24684. this._uniformBuffer.dispose();
  24685. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24686. if (forceDisposeEffect && this._effect) {
  24687. if (this.storeEffectOnSubMeshes) {
  24688. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24689. var subMesh = _c[_b];
  24690. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24691. }
  24692. }
  24693. else {
  24694. this._scene.getEngine()._releaseEffect(this._effect);
  24695. }
  24696. this._effect = null;
  24697. }
  24698. // Callback
  24699. this.onDisposeObservable.notifyObservers(this);
  24700. this.onDisposeObservable.clear();
  24701. this.onBindObservable.clear();
  24702. this.onUnBindObservable.clear();
  24703. };
  24704. Material.prototype.serialize = function () {
  24705. return BABYLON.SerializationHelper.Serialize(this);
  24706. };
  24707. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24708. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24709. multiMaterial.id = parsedMultiMaterial.id;
  24710. if (BABYLON.Tags) {
  24711. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24712. }
  24713. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24714. var subMatId = parsedMultiMaterial.materials[matIndex];
  24715. if (subMatId) {
  24716. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24717. }
  24718. else {
  24719. multiMaterial.subMaterials.push(null);
  24720. }
  24721. }
  24722. return multiMaterial;
  24723. };
  24724. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24725. if (!parsedMaterial.customType) {
  24726. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24727. }
  24728. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  24729. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24730. if (!BABYLON.LegacyPBRMaterial) {
  24731. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24732. return;
  24733. }
  24734. }
  24735. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24736. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24737. ;
  24738. };
  24739. return Material;
  24740. }());
  24741. Material._TriangleFillMode = 0;
  24742. Material._WireFrameFillMode = 1;
  24743. Material._PointFillMode = 2;
  24744. Material._ClockWiseSideOrientation = 0;
  24745. Material._CounterClockWiseSideOrientation = 1;
  24746. Material._TextureDirtyFlag = 1;
  24747. Material._LightDirtyFlag = 2;
  24748. Material._FresnelDirtyFlag = 4;
  24749. Material._AttributesDirtyFlag = 8;
  24750. Material._MiscDirtyFlag = 16;
  24751. __decorate([
  24752. BABYLON.serialize()
  24753. ], Material.prototype, "id", void 0);
  24754. __decorate([
  24755. BABYLON.serialize()
  24756. ], Material.prototype, "name", void 0);
  24757. __decorate([
  24758. BABYLON.serialize()
  24759. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24760. __decorate([
  24761. BABYLON.serialize()
  24762. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24763. __decorate([
  24764. BABYLON.serialize()
  24765. ], Material.prototype, "state", void 0);
  24766. __decorate([
  24767. BABYLON.serialize()
  24768. ], Material.prototype, "alpha", void 0);
  24769. __decorate([
  24770. BABYLON.serialize("backFaceCulling")
  24771. ], Material.prototype, "_backFaceCulling", void 0);
  24772. __decorate([
  24773. BABYLON.serialize()
  24774. ], Material.prototype, "sideOrientation", void 0);
  24775. __decorate([
  24776. BABYLON.serialize()
  24777. ], Material.prototype, "alphaMode", void 0);
  24778. __decorate([
  24779. BABYLON.serialize()
  24780. ], Material.prototype, "disableDepthWrite", void 0);
  24781. __decorate([
  24782. BABYLON.serialize("fogEnabled")
  24783. ], Material.prototype, "_fogEnabled", void 0);
  24784. __decorate([
  24785. BABYLON.serialize()
  24786. ], Material.prototype, "pointSize", void 0);
  24787. __decorate([
  24788. BABYLON.serialize()
  24789. ], Material.prototype, "zOffset", void 0);
  24790. __decorate([
  24791. BABYLON.serialize()
  24792. ], Material.prototype, "wireframe", null);
  24793. __decorate([
  24794. BABYLON.serialize()
  24795. ], Material.prototype, "pointsCloud", null);
  24796. __decorate([
  24797. BABYLON.serialize()
  24798. ], Material.prototype, "fillMode", null);
  24799. BABYLON.Material = Material;
  24800. })(BABYLON || (BABYLON = {}));
  24801. //# sourceMappingURL=babylon.material.js.map
  24802. var BABYLON;
  24803. (function (BABYLON) {
  24804. var UniformBuffer = (function () {
  24805. /**
  24806. * Uniform buffer objects.
  24807. *
  24808. * Handles blocks of uniform on the GPU.
  24809. *
  24810. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24811. *
  24812. * For more information, please refer to :
  24813. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24814. */
  24815. function UniformBuffer(engine, data, dynamic) {
  24816. this._engine = engine;
  24817. this._noUBO = engine.webGLVersion === 1;
  24818. this._dynamic = dynamic;
  24819. this._data = data || [];
  24820. this._uniformLocations = {};
  24821. this._uniformSizes = {};
  24822. this._uniformLocationPointer = 0;
  24823. this._needSync = false;
  24824. if (this._noUBO) {
  24825. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24826. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24827. this.updateFloat = this._updateFloatForEffect;
  24828. this.updateFloat2 = this._updateFloat2ForEffect;
  24829. this.updateFloat3 = this._updateFloat3ForEffect;
  24830. this.updateFloat4 = this._updateFloat4ForEffect;
  24831. this.updateMatrix = this._updateMatrixForEffect;
  24832. this.updateVector3 = this._updateVector3ForEffect;
  24833. this.updateVector4 = this._updateVector4ForEffect;
  24834. this.updateColor3 = this._updateColor3ForEffect;
  24835. this.updateColor4 = this._updateColor4ForEffect;
  24836. }
  24837. else {
  24838. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24839. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24840. this.updateFloat = this._updateFloatForUniform;
  24841. this.updateFloat2 = this._updateFloat2ForUniform;
  24842. this.updateFloat3 = this._updateFloat3ForUniform;
  24843. this.updateFloat4 = this._updateFloat4ForUniform;
  24844. this.updateMatrix = this._updateMatrixForUniform;
  24845. this.updateVector3 = this._updateVector3ForUniform;
  24846. this.updateVector4 = this._updateVector4ForUniform;
  24847. this.updateColor3 = this._updateColor3ForUniform;
  24848. this.updateColor4 = this._updateColor4ForUniform;
  24849. }
  24850. }
  24851. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24852. // Properties
  24853. /**
  24854. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24855. * or just falling back on setUniformXXX calls.
  24856. */
  24857. get: function () {
  24858. return !this._noUBO;
  24859. },
  24860. enumerable: true,
  24861. configurable: true
  24862. });
  24863. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24864. /**
  24865. * Indicates if the WebGL underlying uniform buffer is in sync
  24866. * with the javascript cache data.
  24867. */
  24868. get: function () {
  24869. return !this._needSync;
  24870. },
  24871. enumerable: true,
  24872. configurable: true
  24873. });
  24874. /**
  24875. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24876. * Also, a dynamic UniformBuffer will disable cache verification and always
  24877. * update the underlying WebGL uniform buffer to the GPU.
  24878. */
  24879. UniformBuffer.prototype.isDynamic = function () {
  24880. return this._dynamic;
  24881. };
  24882. /**
  24883. * The data cache on JS side.
  24884. */
  24885. UniformBuffer.prototype.getData = function () {
  24886. return this._bufferData;
  24887. };
  24888. /**
  24889. * The underlying WebGL Uniform buffer.
  24890. */
  24891. UniformBuffer.prototype.getBuffer = function () {
  24892. return this._buffer;
  24893. };
  24894. /**
  24895. * std140 layout specifies how to align data within an UBO structure.
  24896. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24897. * for specs.
  24898. */
  24899. UniformBuffer.prototype._fillAlignment = function (size) {
  24900. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24901. // and 4x4 matrices
  24902. // TODO : change if other types are used
  24903. var alignment;
  24904. if (size <= 2) {
  24905. alignment = size;
  24906. }
  24907. else {
  24908. alignment = 4;
  24909. }
  24910. if ((this._uniformLocationPointer % alignment) !== 0) {
  24911. var oldPointer = this._uniformLocationPointer;
  24912. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24913. var diff = this._uniformLocationPointer - oldPointer;
  24914. for (var i = 0; i < diff; i++) {
  24915. this._data.push(0);
  24916. }
  24917. }
  24918. };
  24919. /**
  24920. * Adds an uniform in the buffer.
  24921. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24922. * for the layout to be correct !
  24923. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24924. * @param {number|number[]} size Data size, or data directly.
  24925. */
  24926. UniformBuffer.prototype.addUniform = function (name, size) {
  24927. if (this._noUBO) {
  24928. return;
  24929. }
  24930. if (this._uniformLocations[name] !== undefined) {
  24931. // Already existing uniform
  24932. return;
  24933. }
  24934. // This function must be called in the order of the shader layout !
  24935. // size can be the size of the uniform, or data directly
  24936. var data;
  24937. if (size instanceof Array) {
  24938. data = size;
  24939. size = data.length;
  24940. }
  24941. else {
  24942. size = size;
  24943. data = [];
  24944. // Fill with zeros
  24945. for (var i = 0; i < size; i++) {
  24946. data.push(0);
  24947. }
  24948. }
  24949. this._fillAlignment(size);
  24950. this._uniformSizes[name] = size;
  24951. this._uniformLocations[name] = this._uniformLocationPointer;
  24952. this._uniformLocationPointer += size;
  24953. for (var i = 0; i < size; i++) {
  24954. this._data.push(data[i]);
  24955. }
  24956. this._needSync = true;
  24957. };
  24958. /**
  24959. * Wrapper for addUniform.
  24960. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24961. * @param {Matrix} mat A 4x4 matrix.
  24962. */
  24963. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24964. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24965. };
  24966. /**
  24967. * Wrapper for addUniform.
  24968. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24969. * @param {number} x
  24970. * @param {number} y
  24971. */
  24972. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24973. var temp = [x, y];
  24974. this.addUniform(name, temp);
  24975. };
  24976. /**
  24977. * Wrapper for addUniform.
  24978. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24979. * @param {number} x
  24980. * @param {number} y
  24981. * @param {number} z
  24982. */
  24983. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24984. var temp = [x, y, z];
  24985. this.addUniform(name, temp);
  24986. };
  24987. /**
  24988. * Wrapper for addUniform.
  24989. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24990. * @param {Color3} color
  24991. */
  24992. UniformBuffer.prototype.addColor3 = function (name, color) {
  24993. var temp = [];
  24994. color.toArray(temp);
  24995. this.addUniform(name, temp);
  24996. };
  24997. /**
  24998. * Wrapper for addUniform.
  24999. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25000. * @param {Color3} color
  25001. * @param {number} alpha
  25002. */
  25003. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25004. var temp = [];
  25005. color.toArray(temp);
  25006. temp.push(alpha);
  25007. this.addUniform(name, temp);
  25008. };
  25009. /**
  25010. * Wrapper for addUniform.
  25011. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25012. * @param {Vector3} vector
  25013. */
  25014. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25015. var temp = [];
  25016. vector.toArray(temp);
  25017. this.addUniform(name, temp);
  25018. };
  25019. /**
  25020. * Wrapper for addUniform.
  25021. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25022. */
  25023. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25024. this.addUniform(name, 12);
  25025. };
  25026. /**
  25027. * Wrapper for addUniform.
  25028. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25029. */
  25030. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25031. this.addUniform(name, 8);
  25032. };
  25033. /**
  25034. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  25035. */
  25036. UniformBuffer.prototype.create = function () {
  25037. if (this._noUBO) {
  25038. return;
  25039. }
  25040. if (this._buffer) {
  25041. return; // nothing to do
  25042. }
  25043. // See spec, alignment must be filled as a vec4
  25044. this._fillAlignment(4);
  25045. this._bufferData = new Float32Array(this._data);
  25046. if (this._dynamic) {
  25047. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  25048. }
  25049. else {
  25050. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  25051. }
  25052. this._needSync = true;
  25053. };
  25054. /**
  25055. * Updates the WebGL Uniform Buffer on the GPU.
  25056. * If the `dynamic` flag is set to true, no cache comparison is done.
  25057. * Otherwise, the buffer will be updated only if the cache differs.
  25058. */
  25059. UniformBuffer.prototype.update = function () {
  25060. if (!this._buffer) {
  25061. this.create();
  25062. return;
  25063. }
  25064. if (!this._dynamic && !this._needSync) {
  25065. return;
  25066. }
  25067. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  25068. this._needSync = false;
  25069. };
  25070. /**
  25071. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  25072. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25073. * @param {number[]|Float32Array} data Flattened data
  25074. * @param {number} size Size of the data.
  25075. */
  25076. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  25077. var location = this._uniformLocations[uniformName];
  25078. if (location === undefined) {
  25079. if (this._buffer) {
  25080. // Cannot add an uniform if the buffer is already created
  25081. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  25082. return;
  25083. }
  25084. this.addUniform(uniformName, size);
  25085. location = this._uniformLocations[uniformName];
  25086. }
  25087. if (!this._buffer) {
  25088. this.create();
  25089. }
  25090. if (!this._dynamic) {
  25091. // Cache for static uniform buffers
  25092. var changed = false;
  25093. for (var i = 0; i < size; i++) {
  25094. if (this._bufferData[location + i] !== data[i]) {
  25095. changed = true;
  25096. this._bufferData[location + i] = data[i];
  25097. }
  25098. }
  25099. this._needSync = this._needSync || changed;
  25100. }
  25101. else {
  25102. // No cache for dynamic
  25103. for (var i = 0; i < size; i++) {
  25104. this._bufferData[location + i] = data[i];
  25105. }
  25106. }
  25107. };
  25108. // Update methods
  25109. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  25110. // To match std140, matrix must be realigned
  25111. for (var i = 0; i < 3; i++) {
  25112. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  25113. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  25114. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  25115. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25116. }
  25117. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  25118. };
  25119. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  25120. this._currentEffect.setMatrix3x3(name, matrix);
  25121. };
  25122. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  25123. this._currentEffect.setMatrix2x2(name, matrix);
  25124. };
  25125. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  25126. // To match std140, matrix must be realigned
  25127. for (var i = 0; i < 2; i++) {
  25128. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  25129. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  25130. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  25131. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25132. }
  25133. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  25134. };
  25135. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  25136. this._currentEffect.setFloat(name, x);
  25137. };
  25138. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  25139. UniformBuffer._tempBuffer[0] = x;
  25140. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  25141. };
  25142. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  25143. if (suffix === void 0) { suffix = ""; }
  25144. this._currentEffect.setFloat2(name + suffix, x, y);
  25145. };
  25146. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  25147. if (suffix === void 0) { suffix = ""; }
  25148. UniformBuffer._tempBuffer[0] = x;
  25149. UniformBuffer._tempBuffer[1] = y;
  25150. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  25151. };
  25152. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  25153. if (suffix === void 0) { suffix = ""; }
  25154. this._currentEffect.setFloat3(name + suffix, x, y, z);
  25155. };
  25156. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  25157. if (suffix === void 0) { suffix = ""; }
  25158. UniformBuffer._tempBuffer[0] = x;
  25159. UniformBuffer._tempBuffer[1] = y;
  25160. UniformBuffer._tempBuffer[2] = z;
  25161. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25162. };
  25163. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  25164. if (suffix === void 0) { suffix = ""; }
  25165. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  25166. };
  25167. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  25168. if (suffix === void 0) { suffix = ""; }
  25169. UniformBuffer._tempBuffer[0] = x;
  25170. UniformBuffer._tempBuffer[1] = y;
  25171. UniformBuffer._tempBuffer[2] = z;
  25172. UniformBuffer._tempBuffer[3] = w;
  25173. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25174. };
  25175. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  25176. this._currentEffect.setMatrix(name, mat);
  25177. };
  25178. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  25179. this.updateUniform(name, mat.toArray(), 16);
  25180. };
  25181. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  25182. this._currentEffect.setVector3(name, vector);
  25183. };
  25184. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  25185. vector.toArray(UniformBuffer._tempBuffer);
  25186. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25187. };
  25188. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  25189. this._currentEffect.setVector4(name, vector);
  25190. };
  25191. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  25192. vector.toArray(UniformBuffer._tempBuffer);
  25193. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25194. };
  25195. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  25196. if (suffix === void 0) { suffix = ""; }
  25197. this._currentEffect.setColor3(name + suffix, color);
  25198. };
  25199. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  25200. if (suffix === void 0) { suffix = ""; }
  25201. color.toArray(UniformBuffer._tempBuffer);
  25202. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25203. };
  25204. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  25205. if (suffix === void 0) { suffix = ""; }
  25206. this._currentEffect.setColor4(name + suffix, color, alpha);
  25207. };
  25208. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  25209. if (suffix === void 0) { suffix = ""; }
  25210. color.toArray(UniformBuffer._tempBuffer);
  25211. UniformBuffer._tempBuffer[3] = alpha;
  25212. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25213. };
  25214. /**
  25215. * Sets a sampler uniform on the effect.
  25216. * @param {string} name Name of the sampler.
  25217. * @param {Texture} texture
  25218. */
  25219. UniformBuffer.prototype.setTexture = function (name, texture) {
  25220. this._currentEffect.setTexture(name, texture);
  25221. };
  25222. /**
  25223. * Directly updates the value of the uniform in the cache AND on the GPU.
  25224. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25225. * @param {number[]|Float32Array} data Flattened data
  25226. */
  25227. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  25228. this.updateUniform(uniformName, data, data.length);
  25229. this.update();
  25230. };
  25231. /**
  25232. * Binds this uniform buffer to an effect.
  25233. * @param {Effect} effect
  25234. * @param {string} name Name of the uniform block in the shader.
  25235. */
  25236. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  25237. this._currentEffect = effect;
  25238. if (this._noUBO) {
  25239. return;
  25240. }
  25241. effect.bindUniformBuffer(this._buffer, name);
  25242. };
  25243. /**
  25244. * Disposes the uniform buffer.
  25245. */
  25246. UniformBuffer.prototype.dispose = function () {
  25247. if (!this._buffer) {
  25248. return;
  25249. }
  25250. if (this._engine._releaseBuffer(this._buffer)) {
  25251. this._buffer = null;
  25252. }
  25253. };
  25254. return UniformBuffer;
  25255. }());
  25256. // Pool for avoiding memory leaks
  25257. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  25258. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  25259. BABYLON.UniformBuffer = UniformBuffer;
  25260. })(BABYLON || (BABYLON = {}));
  25261. //# sourceMappingURL=babylon.uniformBuffer.js.map
  25262. var BABYLON;
  25263. (function (BABYLON) {
  25264. var PushMaterial = (function (_super) {
  25265. __extends(PushMaterial, _super);
  25266. function PushMaterial(name, scene) {
  25267. var _this = _super.call(this, name, scene) || this;
  25268. _this.storeEffectOnSubMeshes = true;
  25269. return _this;
  25270. }
  25271. PushMaterial.prototype.getEffect = function () {
  25272. return this._activeEffect;
  25273. };
  25274. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  25275. if (!mesh) {
  25276. return false;
  25277. }
  25278. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25279. return true;
  25280. }
  25281. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  25282. };
  25283. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25284. this._activeEffect.setMatrix("world", world);
  25285. };
  25286. PushMaterial.prototype.bind = function (world, mesh) {
  25287. if (!mesh) {
  25288. return;
  25289. }
  25290. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  25291. };
  25292. PushMaterial.prototype._afterBind = function (mesh, effect) {
  25293. _super.prototype._afterBind.call(this, mesh);
  25294. this.getScene()._cachedEffect = effect;
  25295. };
  25296. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  25297. if (visibility === void 0) { visibility = 0; }
  25298. return scene.isCachedMaterialValid(this, effect, visibility);
  25299. };
  25300. return PushMaterial;
  25301. }(BABYLON.Material));
  25302. BABYLON.PushMaterial = PushMaterial;
  25303. })(BABYLON || (BABYLON = {}));
  25304. //# sourceMappingURL=babylon.pushMaterial.js.map
  25305. var BABYLON;
  25306. (function (BABYLON) {
  25307. var VertexData = (function () {
  25308. function VertexData() {
  25309. }
  25310. VertexData.prototype.set = function (data, kind) {
  25311. switch (kind) {
  25312. case BABYLON.VertexBuffer.PositionKind:
  25313. this.positions = data;
  25314. break;
  25315. case BABYLON.VertexBuffer.NormalKind:
  25316. this.normals = data;
  25317. break;
  25318. case BABYLON.VertexBuffer.TangentKind:
  25319. this.tangents = data;
  25320. break;
  25321. case BABYLON.VertexBuffer.UVKind:
  25322. this.uvs = data;
  25323. break;
  25324. case BABYLON.VertexBuffer.UV2Kind:
  25325. this.uvs2 = data;
  25326. break;
  25327. case BABYLON.VertexBuffer.UV3Kind:
  25328. this.uvs3 = data;
  25329. break;
  25330. case BABYLON.VertexBuffer.UV4Kind:
  25331. this.uvs4 = data;
  25332. break;
  25333. case BABYLON.VertexBuffer.UV5Kind:
  25334. this.uvs5 = data;
  25335. break;
  25336. case BABYLON.VertexBuffer.UV6Kind:
  25337. this.uvs6 = data;
  25338. break;
  25339. case BABYLON.VertexBuffer.ColorKind:
  25340. this.colors = data;
  25341. break;
  25342. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25343. this.matricesIndices = data;
  25344. break;
  25345. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25346. this.matricesWeights = data;
  25347. break;
  25348. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  25349. this.matricesIndicesExtra = data;
  25350. break;
  25351. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  25352. this.matricesWeightsExtra = data;
  25353. break;
  25354. }
  25355. };
  25356. /**
  25357. * Associates the vertexData to the passed Mesh.
  25358. * Sets it as updatable or not (default `false`).
  25359. * Returns the VertexData.
  25360. */
  25361. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25362. this._applyTo(mesh, updatable);
  25363. return this;
  25364. };
  25365. /**
  25366. * Associates the vertexData to the passed Geometry.
  25367. * Sets it as updatable or not (default `false`).
  25368. * Returns the VertexData.
  25369. */
  25370. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25371. this._applyTo(geometry, updatable);
  25372. return this;
  25373. };
  25374. /**
  25375. * Updates the associated mesh.
  25376. * Returns the VertexData.
  25377. */
  25378. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25379. this._update(mesh);
  25380. return this;
  25381. };
  25382. /**
  25383. * Updates the associated geometry.
  25384. * Returns the VertexData.
  25385. */
  25386. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25387. this._update(geometry);
  25388. return this;
  25389. };
  25390. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25391. if (this.positions) {
  25392. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25393. }
  25394. if (this.normals) {
  25395. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25396. }
  25397. if (this.tangents) {
  25398. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25399. }
  25400. if (this.uvs) {
  25401. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25402. }
  25403. if (this.uvs2) {
  25404. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25405. }
  25406. if (this.uvs3) {
  25407. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25408. }
  25409. if (this.uvs4) {
  25410. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25411. }
  25412. if (this.uvs5) {
  25413. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25414. }
  25415. if (this.uvs6) {
  25416. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25417. }
  25418. if (this.colors) {
  25419. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25420. }
  25421. if (this.matricesIndices) {
  25422. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25423. }
  25424. if (this.matricesWeights) {
  25425. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25426. }
  25427. if (this.matricesIndicesExtra) {
  25428. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25429. }
  25430. if (this.matricesWeightsExtra) {
  25431. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25432. }
  25433. if (this.indices) {
  25434. meshOrGeometry.setIndices(this.indices);
  25435. }
  25436. return this;
  25437. };
  25438. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25439. if (this.positions) {
  25440. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25441. }
  25442. if (this.normals) {
  25443. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25444. }
  25445. if (this.tangents) {
  25446. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25447. }
  25448. if (this.uvs) {
  25449. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25450. }
  25451. if (this.uvs2) {
  25452. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25453. }
  25454. if (this.uvs3) {
  25455. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25456. }
  25457. if (this.uvs4) {
  25458. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25459. }
  25460. if (this.uvs5) {
  25461. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25462. }
  25463. if (this.uvs6) {
  25464. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25465. }
  25466. if (this.colors) {
  25467. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25468. }
  25469. if (this.matricesIndices) {
  25470. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25471. }
  25472. if (this.matricesWeights) {
  25473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25474. }
  25475. if (this.matricesIndicesExtra) {
  25476. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25477. }
  25478. if (this.matricesWeightsExtra) {
  25479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25480. }
  25481. if (this.indices) {
  25482. meshOrGeometry.setIndices(this.indices);
  25483. }
  25484. return this;
  25485. };
  25486. /**
  25487. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  25488. * Returns the VertexData.
  25489. */
  25490. VertexData.prototype.transform = function (matrix) {
  25491. var transformed = BABYLON.Vector3.Zero();
  25492. var index;
  25493. if (this.positions) {
  25494. var position = BABYLON.Vector3.Zero();
  25495. for (index = 0; index < this.positions.length; index += 3) {
  25496. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25497. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25498. this.positions[index] = transformed.x;
  25499. this.positions[index + 1] = transformed.y;
  25500. this.positions[index + 2] = transformed.z;
  25501. }
  25502. }
  25503. if (this.normals) {
  25504. var normal = BABYLON.Vector3.Zero();
  25505. for (index = 0; index < this.normals.length; index += 3) {
  25506. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25507. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25508. this.normals[index] = transformed.x;
  25509. this.normals[index + 1] = transformed.y;
  25510. this.normals[index + 2] = transformed.z;
  25511. }
  25512. }
  25513. if (this.tangents) {
  25514. var tangent = BABYLON.Vector4.Zero();
  25515. var tangentTransformed = BABYLON.Vector4.Zero();
  25516. for (index = 0; index < this.tangents.length; index += 4) {
  25517. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  25518. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  25519. this.tangents[index] = tangentTransformed.x;
  25520. this.tangents[index + 1] = tangentTransformed.y;
  25521. this.tangents[index + 2] = tangentTransformed.z;
  25522. this.tangents[index + 3] = tangentTransformed.w;
  25523. }
  25524. }
  25525. return this;
  25526. };
  25527. /**
  25528. * Merges the passed VertexData into the current one.
  25529. * Returns the modified VertexData.
  25530. */
  25531. VertexData.prototype.merge = function (other) {
  25532. if (other.indices) {
  25533. if (!this.indices) {
  25534. this.indices = [];
  25535. }
  25536. var offset = this.positions ? this.positions.length / 3 : 0;
  25537. for (var index = 0; index < other.indices.length; index++) {
  25538. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  25539. this.indices.push(other.indices[index] + offset);
  25540. }
  25541. }
  25542. this.positions = this._mergeElement(this.positions, other.positions);
  25543. this.normals = this._mergeElement(this.normals, other.normals);
  25544. this.tangents = this._mergeElement(this.tangents, other.tangents);
  25545. this.uvs = this._mergeElement(this.uvs, other.uvs);
  25546. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  25547. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  25548. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  25549. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  25550. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  25551. this.colors = this._mergeElement(this.colors, other.colors);
  25552. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  25553. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  25554. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  25555. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  25556. return this;
  25557. };
  25558. VertexData.prototype._mergeElement = function (source, other) {
  25559. if (!other)
  25560. return source;
  25561. if (!source)
  25562. return other;
  25563. var len = other.length + source.length;
  25564. var isSrcTypedArray = source instanceof Float32Array;
  25565. var isOthTypedArray = other instanceof Float32Array;
  25566. // use non-loop method when the source is Float32Array
  25567. if (isSrcTypedArray) {
  25568. var ret32 = new Float32Array(len);
  25569. ret32.set(source);
  25570. ret32.set(other, source.length);
  25571. return ret32;
  25572. // source is number[], when other is also use concat
  25573. }
  25574. else if (!isOthTypedArray) {
  25575. return source.concat(other);
  25576. // source is a number[], but other is a Float32Array, loop required
  25577. }
  25578. else {
  25579. var ret = source.slice(0); // copy source to a separate array
  25580. for (var i = 0, len = other.length; i < len; i++) {
  25581. ret.push(other[i]);
  25582. }
  25583. return ret;
  25584. }
  25585. };
  25586. /**
  25587. * Serializes the VertexData.
  25588. * Returns a serialized object.
  25589. */
  25590. VertexData.prototype.serialize = function () {
  25591. var serializationObject = this.serialize();
  25592. if (this.positions) {
  25593. serializationObject.positions = this.positions;
  25594. }
  25595. if (this.normals) {
  25596. serializationObject.normals = this.normals;
  25597. }
  25598. if (this.tangents) {
  25599. serializationObject.tangents = this.tangents;
  25600. }
  25601. if (this.uvs) {
  25602. serializationObject.uvs = this.uvs;
  25603. }
  25604. if (this.uvs2) {
  25605. serializationObject.uvs2 = this.uvs2;
  25606. }
  25607. if (this.uvs3) {
  25608. serializationObject.uvs3 = this.uvs3;
  25609. }
  25610. if (this.uvs4) {
  25611. serializationObject.uvs4 = this.uvs4;
  25612. }
  25613. if (this.uvs5) {
  25614. serializationObject.uvs5 = this.uvs5;
  25615. }
  25616. if (this.uvs6) {
  25617. serializationObject.uvs6 = this.uvs6;
  25618. }
  25619. if (this.colors) {
  25620. serializationObject.colors = this.colors;
  25621. }
  25622. if (this.matricesIndices) {
  25623. serializationObject.matricesIndices = this.matricesIndices;
  25624. serializationObject.matricesIndices._isExpanded = true;
  25625. }
  25626. if (this.matricesWeights) {
  25627. serializationObject.matricesWeights = this.matricesWeights;
  25628. }
  25629. if (this.matricesIndicesExtra) {
  25630. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25631. serializationObject.matricesIndicesExtra._isExpanded = true;
  25632. }
  25633. if (this.matricesWeightsExtra) {
  25634. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25635. }
  25636. serializationObject.indices = this.indices;
  25637. return serializationObject;
  25638. };
  25639. // Statics
  25640. /**
  25641. * Returns the object VertexData associated to the passed mesh.
  25642. */
  25643. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25644. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25645. };
  25646. /**
  25647. * Returns the object VertexData associated to the passed geometry.
  25648. */
  25649. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25650. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25651. };
  25652. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25653. var result = new VertexData();
  25654. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25655. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25656. }
  25657. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25658. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25659. }
  25660. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25661. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25662. }
  25663. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25664. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25665. }
  25666. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25667. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25668. }
  25669. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25670. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25671. }
  25672. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25673. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25674. }
  25675. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25676. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25677. }
  25678. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25679. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25680. }
  25681. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25682. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25683. }
  25684. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25685. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25686. }
  25687. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25688. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25689. }
  25690. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25691. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25692. }
  25693. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25694. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25695. }
  25696. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25697. return result;
  25698. };
  25699. /**
  25700. * Creates the vertexData of the Ribbon.
  25701. */
  25702. VertexData.CreateRibbon = function (options) {
  25703. var pathArray = options.pathArray;
  25704. var closeArray = options.closeArray || false;
  25705. var closePath = options.closePath || false;
  25706. var invertUV = options.invertUV || false;
  25707. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25708. var offset = options.offset || defaultOffset;
  25709. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25710. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25711. var customUV = options.uvs;
  25712. var customColors = options.colors;
  25713. var positions = [];
  25714. var indices = [];
  25715. var normals = [];
  25716. var uvs = [];
  25717. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25718. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25719. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25720. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25721. var minlg; // minimal length among all paths from pathArray
  25722. var lg = []; // array of path lengths : nb of vertex per path
  25723. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25724. var p; // path iterator
  25725. var i; // point iterator
  25726. var j; // point iterator
  25727. // if single path in pathArray
  25728. if (pathArray.length < 2) {
  25729. var ar1 = [];
  25730. var ar2 = [];
  25731. for (i = 0; i < pathArray[0].length - offset; i++) {
  25732. ar1.push(pathArray[0][i]);
  25733. ar2.push(pathArray[0][i + offset]);
  25734. }
  25735. pathArray = [ar1, ar2];
  25736. }
  25737. // positions and horizontal distances (u)
  25738. var idc = 0;
  25739. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25740. var path;
  25741. var l;
  25742. minlg = pathArray[0].length;
  25743. var vectlg;
  25744. var dist;
  25745. for (p = 0; p < pathArray.length; p++) {
  25746. uTotalDistance[p] = 0;
  25747. us[p] = [0];
  25748. path = pathArray[p];
  25749. l = path.length;
  25750. minlg = (minlg < l) ? minlg : l;
  25751. j = 0;
  25752. while (j < l) {
  25753. positions.push(path[j].x, path[j].y, path[j].z);
  25754. if (j > 0) {
  25755. vectlg = path[j].subtract(path[j - 1]).length();
  25756. dist = vectlg + uTotalDistance[p];
  25757. us[p].push(dist);
  25758. uTotalDistance[p] = dist;
  25759. }
  25760. j++;
  25761. }
  25762. if (closePath) {
  25763. j--;
  25764. positions.push(path[0].x, path[0].y, path[0].z);
  25765. vectlg = path[j].subtract(path[0]).length();
  25766. dist = vectlg + uTotalDistance[p];
  25767. us[p].push(dist);
  25768. uTotalDistance[p] = dist;
  25769. }
  25770. lg[p] = l + closePathCorr;
  25771. idx[p] = idc;
  25772. idc += (l + closePathCorr);
  25773. }
  25774. // vertical distances (v)
  25775. var path1;
  25776. var path2;
  25777. var vertex1;
  25778. var vertex2;
  25779. for (i = 0; i < minlg + closePathCorr; i++) {
  25780. vTotalDistance[i] = 0;
  25781. vs[i] = [0];
  25782. for (p = 0; p < pathArray.length - 1; p++) {
  25783. path1 = pathArray[p];
  25784. path2 = pathArray[p + 1];
  25785. if (i === minlg) {
  25786. vertex1 = path1[0];
  25787. vertex2 = path2[0];
  25788. }
  25789. else {
  25790. vertex1 = path1[i];
  25791. vertex2 = path2[i];
  25792. }
  25793. vectlg = vertex2.subtract(vertex1).length();
  25794. dist = vectlg + vTotalDistance[i];
  25795. vs[i].push(dist);
  25796. vTotalDistance[i] = dist;
  25797. }
  25798. if (closeArray) {
  25799. path1 = pathArray[p];
  25800. path2 = pathArray[0];
  25801. if (i === minlg) {
  25802. vertex2 = path2[0];
  25803. }
  25804. vectlg = vertex2.subtract(vertex1).length();
  25805. dist = vectlg + vTotalDistance[i];
  25806. vTotalDistance[i] = dist;
  25807. }
  25808. }
  25809. // uvs
  25810. var u;
  25811. var v;
  25812. if (customUV) {
  25813. for (p = 0; p < customUV.length; p++) {
  25814. uvs.push(customUV[p].x, customUV[p].y);
  25815. }
  25816. }
  25817. else {
  25818. for (p = 0; p < pathArray.length; p++) {
  25819. for (i = 0; i < minlg + closePathCorr; i++) {
  25820. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25821. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25822. if (invertUV) {
  25823. uvs.push(v, u);
  25824. }
  25825. else {
  25826. uvs.push(u, v);
  25827. }
  25828. }
  25829. }
  25830. }
  25831. // indices
  25832. p = 0; // path index
  25833. var pi = 0; // positions array index
  25834. var l1 = lg[p] - 1; // path1 length
  25835. var l2 = lg[p + 1] - 1; // path2 length
  25836. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25837. var shft = idx[1] - idx[0]; // shift
  25838. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25839. while (pi <= min && p < path1nb) {
  25840. // 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
  25841. indices.push(pi, pi + shft, pi + 1);
  25842. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25843. pi += 1;
  25844. if (pi === min) {
  25845. p++;
  25846. if (p === lg.length - 1) {
  25847. shft = idx[0] - idx[p];
  25848. l1 = lg[p] - 1;
  25849. l2 = lg[0] - 1;
  25850. }
  25851. else {
  25852. shft = idx[p + 1] - idx[p];
  25853. l1 = lg[p] - 1;
  25854. l2 = lg[p + 1] - 1;
  25855. }
  25856. pi = idx[p];
  25857. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25858. }
  25859. }
  25860. // normals
  25861. VertexData.ComputeNormals(positions, indices, normals);
  25862. if (closePath) {
  25863. var indexFirst = 0;
  25864. var indexLast = 0;
  25865. for (p = 0; p < pathArray.length; p++) {
  25866. indexFirst = idx[p] * 3;
  25867. if (p + 1 < pathArray.length) {
  25868. indexLast = (idx[p + 1] - 1) * 3;
  25869. }
  25870. else {
  25871. indexLast = normals.length - 3;
  25872. }
  25873. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25874. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25875. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25876. normals[indexLast] = normals[indexFirst];
  25877. normals[indexLast + 1] = normals[indexFirst + 1];
  25878. normals[indexLast + 2] = normals[indexFirst + 2];
  25879. }
  25880. }
  25881. // sides
  25882. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25883. // Colors
  25884. if (customColors) {
  25885. var colors = new Float32Array(customColors.length * 4);
  25886. for (var c = 0; c < customColors.length; c++) {
  25887. colors[c * 4] = customColors[c].r;
  25888. colors[c * 4 + 1] = customColors[c].g;
  25889. colors[c * 4 + 2] = customColors[c].b;
  25890. colors[c * 4 + 3] = customColors[c].a;
  25891. }
  25892. }
  25893. // Result
  25894. var vertexData = new VertexData();
  25895. var positions32 = new Float32Array(positions);
  25896. var normals32 = new Float32Array(normals);
  25897. var uvs32 = new Float32Array(uvs);
  25898. vertexData.indices = indices;
  25899. vertexData.positions = positions32;
  25900. vertexData.normals = normals32;
  25901. vertexData.uvs = uvs32;
  25902. if (customColors) {
  25903. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25904. }
  25905. if (closePath) {
  25906. vertexData._idx = idx;
  25907. }
  25908. return vertexData;
  25909. };
  25910. /**
  25911. * Creates the VertexData of the Box.
  25912. */
  25913. VertexData.CreateBox = function (options) {
  25914. var normalsSource = [
  25915. new BABYLON.Vector3(0, 0, 1),
  25916. new BABYLON.Vector3(0, 0, -1),
  25917. new BABYLON.Vector3(1, 0, 0),
  25918. new BABYLON.Vector3(-1, 0, 0),
  25919. new BABYLON.Vector3(0, 1, 0),
  25920. new BABYLON.Vector3(0, -1, 0)
  25921. ];
  25922. var indices = [];
  25923. var positions = [];
  25924. var normals = [];
  25925. var uvs = [];
  25926. var width = options.width || options.size || 1;
  25927. var height = options.height || options.size || 1;
  25928. var depth = options.depth || options.size || 1;
  25929. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25930. var faceUV = options.faceUV || new Array(6);
  25931. var faceColors = options.faceColors;
  25932. var colors = [];
  25933. // default face colors and UV if undefined
  25934. for (var f = 0; f < 6; f++) {
  25935. if (faceUV[f] === undefined) {
  25936. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25937. }
  25938. if (faceColors && faceColors[f] === undefined) {
  25939. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25940. }
  25941. }
  25942. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25943. // Create each face in turn.
  25944. for (var index = 0; index < normalsSource.length; index++) {
  25945. var normal = normalsSource[index];
  25946. // Get two vectors perpendicular to the face normal and to each other.
  25947. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25948. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25949. // Six indices (two triangles) per face.
  25950. var verticesLength = positions.length / 3;
  25951. indices.push(verticesLength);
  25952. indices.push(verticesLength + 1);
  25953. indices.push(verticesLength + 2);
  25954. indices.push(verticesLength);
  25955. indices.push(verticesLength + 2);
  25956. indices.push(verticesLength + 3);
  25957. // Four vertices per face.
  25958. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25959. positions.push(vertex.x, vertex.y, vertex.z);
  25960. normals.push(normal.x, normal.y, normal.z);
  25961. uvs.push(faceUV[index].z, faceUV[index].w);
  25962. if (faceColors) {
  25963. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25964. }
  25965. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25966. positions.push(vertex.x, vertex.y, vertex.z);
  25967. normals.push(normal.x, normal.y, normal.z);
  25968. uvs.push(faceUV[index].x, faceUV[index].w);
  25969. if (faceColors) {
  25970. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25971. }
  25972. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25973. positions.push(vertex.x, vertex.y, vertex.z);
  25974. normals.push(normal.x, normal.y, normal.z);
  25975. uvs.push(faceUV[index].x, faceUV[index].y);
  25976. if (faceColors) {
  25977. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25978. }
  25979. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25980. positions.push(vertex.x, vertex.y, vertex.z);
  25981. normals.push(normal.x, normal.y, normal.z);
  25982. uvs.push(faceUV[index].z, faceUV[index].y);
  25983. if (faceColors) {
  25984. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25985. }
  25986. }
  25987. // sides
  25988. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25989. // Result
  25990. var vertexData = new VertexData();
  25991. vertexData.indices = indices;
  25992. vertexData.positions = positions;
  25993. vertexData.normals = normals;
  25994. vertexData.uvs = uvs;
  25995. if (faceColors) {
  25996. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25997. vertexData.colors = totalColors;
  25998. }
  25999. return vertexData;
  26000. };
  26001. /**
  26002. * Creates the VertexData of the Sphere.
  26003. */
  26004. VertexData.CreateSphere = function (options) {
  26005. var segments = options.segments || 32;
  26006. var diameterX = options.diameterX || options.diameter || 1;
  26007. var diameterY = options.diameterY || options.diameter || 1;
  26008. var diameterZ = options.diameterZ || options.diameter || 1;
  26009. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26010. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26011. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26012. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26013. var totalZRotationSteps = 2 + segments;
  26014. var totalYRotationSteps = 2 * totalZRotationSteps;
  26015. var indices = [];
  26016. var positions = [];
  26017. var normals = [];
  26018. var uvs = [];
  26019. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26020. var normalizedZ = zRotationStep / totalZRotationSteps;
  26021. var angleZ = normalizedZ * Math.PI * slice;
  26022. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26023. var normalizedY = yRotationStep / totalYRotationSteps;
  26024. var angleY = normalizedY * Math.PI * 2 * arc;
  26025. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26026. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26027. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26028. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26029. var vertex = complete.multiply(radius);
  26030. var normal = complete.divide(radius).normalize();
  26031. positions.push(vertex.x, vertex.y, vertex.z);
  26032. normals.push(normal.x, normal.y, normal.z);
  26033. uvs.push(normalizedY, normalizedZ);
  26034. }
  26035. if (zRotationStep > 0) {
  26036. var verticesCount = positions.length / 3;
  26037. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26038. indices.push((firstIndex));
  26039. indices.push((firstIndex + 1));
  26040. indices.push(firstIndex + totalYRotationSteps + 1);
  26041. indices.push((firstIndex + totalYRotationSteps + 1));
  26042. indices.push((firstIndex + 1));
  26043. indices.push((firstIndex + totalYRotationSteps + 2));
  26044. }
  26045. }
  26046. }
  26047. // Sides
  26048. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26049. // Result
  26050. var vertexData = new VertexData();
  26051. vertexData.indices = indices;
  26052. vertexData.positions = positions;
  26053. vertexData.normals = normals;
  26054. vertexData.uvs = uvs;
  26055. return vertexData;
  26056. };
  26057. /**
  26058. * Creates the VertexData of the Cylinder or Cone.
  26059. */
  26060. VertexData.CreateCylinder = function (options) {
  26061. var height = options.height || 2;
  26062. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26063. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  26064. var tessellation = options.tessellation || 24;
  26065. var subdivisions = options.subdivisions || 1;
  26066. var hasRings = options.hasRings;
  26067. var enclose = options.enclose;
  26068. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26069. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26070. var faceUV = options.faceUV || new Array(3);
  26071. var faceColors = options.faceColors;
  26072. // default face colors and UV if undefined
  26073. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  26074. var ringNb = (hasRings) ? subdivisions : 1;
  26075. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  26076. var f;
  26077. for (f = 0; f < surfaceNb; f++) {
  26078. if (faceColors && faceColors[f] === undefined) {
  26079. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26080. }
  26081. }
  26082. for (f = 0; f < surfaceNb; f++) {
  26083. if (faceUV && faceUV[f] === undefined) {
  26084. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26085. }
  26086. }
  26087. var indices = [];
  26088. var positions = [];
  26089. var normals = [];
  26090. var uvs = [];
  26091. var colors = [];
  26092. var angle_step = Math.PI * 2 * arc / tessellation;
  26093. var angle;
  26094. var h;
  26095. var radius;
  26096. var tan = (diameterBottom - diameterTop) / 2 / height;
  26097. var ringVertex = BABYLON.Vector3.Zero();
  26098. var ringNormal = BABYLON.Vector3.Zero();
  26099. var ringFirstVertex = BABYLON.Vector3.Zero();
  26100. var ringFirstNormal = BABYLON.Vector3.Zero();
  26101. var quadNormal = BABYLON.Vector3.Zero();
  26102. var Y = BABYLON.Axis.Y;
  26103. // positions, normals, uvs
  26104. var i;
  26105. var j;
  26106. var r;
  26107. var ringIdx = 1;
  26108. var s = 1; // surface index
  26109. var cs = 0;
  26110. var v = 0;
  26111. for (i = 0; i <= subdivisions; i++) {
  26112. h = i / subdivisions;
  26113. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26114. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  26115. for (r = 0; r < ringIdx; r++) {
  26116. if (hasRings) {
  26117. s += r;
  26118. }
  26119. if (enclose) {
  26120. s += 2 * r;
  26121. }
  26122. for (j = 0; j <= tessellation; j++) {
  26123. angle = j * angle_step;
  26124. // position
  26125. ringVertex.x = Math.cos(-angle) * radius;
  26126. ringVertex.y = -height / 2 + h * height;
  26127. ringVertex.z = Math.sin(-angle) * radius;
  26128. // normal
  26129. if (diameterTop === 0 && i === subdivisions) {
  26130. // if no top cap, reuse former normals
  26131. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26132. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26133. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26134. }
  26135. else {
  26136. ringNormal.x = ringVertex.x;
  26137. ringNormal.z = ringVertex.z;
  26138. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26139. ringNormal.normalize();
  26140. }
  26141. // keep first ring vertex values for enclose
  26142. if (j === 0) {
  26143. ringFirstVertex.copyFrom(ringVertex);
  26144. ringFirstNormal.copyFrom(ringNormal);
  26145. }
  26146. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26147. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26148. if (hasRings) {
  26149. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  26150. }
  26151. else {
  26152. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  26153. }
  26154. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  26155. if (faceColors) {
  26156. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  26157. }
  26158. }
  26159. // if enclose, add four vertices and their dedicated normals
  26160. if (arc !== 1 && enclose) {
  26161. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26162. positions.push(0, ringVertex.y, 0);
  26163. positions.push(0, ringVertex.y, 0);
  26164. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  26165. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  26166. quadNormal.normalize();
  26167. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26168. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  26169. quadNormal.normalize();
  26170. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26171. if (hasRings) {
  26172. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  26173. }
  26174. else {
  26175. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  26176. }
  26177. uvs.push(faceUV[s + 1].x, v);
  26178. uvs.push(faceUV[s + 1].z, v);
  26179. if (hasRings) {
  26180. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  26181. }
  26182. else {
  26183. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  26184. }
  26185. uvs.push(faceUV[s + 2].x, v);
  26186. uvs.push(faceUV[s + 2].z, v);
  26187. if (faceColors) {
  26188. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26189. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26190. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26191. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26192. }
  26193. }
  26194. if (cs !== s) {
  26195. cs = s;
  26196. }
  26197. }
  26198. }
  26199. // indices
  26200. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  26201. var s;
  26202. i = 0;
  26203. for (s = 0; s < subdivisions; s++) {
  26204. for (j = 0; j < tessellation; j++) {
  26205. var i0 = i * (e + 1) + j;
  26206. var i1 = (i + 1) * (e + 1) + j;
  26207. var i2 = i * (e + 1) + (j + 1);
  26208. var i3 = (i + 1) * (e + 1) + (j + 1);
  26209. indices.push(i0, i1, i2);
  26210. indices.push(i3, i2, i1);
  26211. }
  26212. if (arc !== 1 && enclose) {
  26213. indices.push(i0 + 2, i1 + 2, i2 + 2);
  26214. indices.push(i3 + 2, i2 + 2, i1 + 2);
  26215. indices.push(i0 + 4, i1 + 4, i2 + 4);
  26216. indices.push(i3 + 4, i2 + 4, i1 + 4);
  26217. }
  26218. i = (hasRings) ? (i + 2) : (i + 1);
  26219. }
  26220. // Caps
  26221. var createCylinderCap = function (isTop) {
  26222. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26223. if (radius === 0) {
  26224. return;
  26225. }
  26226. // Cap positions, normals & uvs
  26227. var angle;
  26228. var circleVector;
  26229. var i;
  26230. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  26231. var c;
  26232. if (faceColors) {
  26233. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  26234. }
  26235. // cap center
  26236. var vbase = positions.length / 3;
  26237. var offset = isTop ? height / 2 : -height / 2;
  26238. var center = new BABYLON.Vector3(0, offset, 0);
  26239. positions.push(center.x, center.y, center.z);
  26240. normals.push(0, isTop ? 1 : -1, 0);
  26241. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  26242. if (faceColors) {
  26243. colors.push(c.r, c.g, c.b, c.a);
  26244. }
  26245. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26246. for (i = 0; i <= tessellation; i++) {
  26247. angle = Math.PI * 2 * i * arc / tessellation;
  26248. var cos = Math.cos(-angle);
  26249. var sin = Math.sin(-angle);
  26250. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  26251. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  26252. positions.push(circleVector.x, circleVector.y, circleVector.z);
  26253. normals.push(0, isTop ? 1 : -1, 0);
  26254. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  26255. if (faceColors) {
  26256. colors.push(c.r, c.g, c.b, c.a);
  26257. }
  26258. }
  26259. // Cap indices
  26260. for (i = 0; i < tessellation; i++) {
  26261. if (!isTop) {
  26262. indices.push(vbase);
  26263. indices.push(vbase + (i + 1));
  26264. indices.push(vbase + (i + 2));
  26265. }
  26266. else {
  26267. indices.push(vbase);
  26268. indices.push(vbase + (i + 2));
  26269. indices.push(vbase + (i + 1));
  26270. }
  26271. }
  26272. };
  26273. // add caps to geometry
  26274. createCylinderCap(false);
  26275. createCylinderCap(true);
  26276. // Sides
  26277. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26278. var vertexData = new VertexData();
  26279. vertexData.indices = indices;
  26280. vertexData.positions = positions;
  26281. vertexData.normals = normals;
  26282. vertexData.uvs = uvs;
  26283. if (faceColors) {
  26284. vertexData.colors = colors;
  26285. }
  26286. return vertexData;
  26287. };
  26288. /**
  26289. * Creates the VertexData of the Torus.
  26290. */
  26291. VertexData.CreateTorus = function (options) {
  26292. var indices = [];
  26293. var positions = [];
  26294. var normals = [];
  26295. var uvs = [];
  26296. var diameter = options.diameter || 1;
  26297. var thickness = options.thickness || 0.5;
  26298. var tessellation = options.tessellation || 16;
  26299. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26300. var stride = tessellation + 1;
  26301. for (var i = 0; i <= tessellation; i++) {
  26302. var u = i / tessellation;
  26303. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26304. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26305. for (var j = 0; j <= tessellation; j++) {
  26306. var v = 1 - j / tessellation;
  26307. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26308. var dx = Math.cos(innerAngle);
  26309. var dy = Math.sin(innerAngle);
  26310. // Create a vertex.
  26311. var normal = new BABYLON.Vector3(dx, dy, 0);
  26312. var position = normal.scale(thickness / 2);
  26313. var textureCoordinate = new BABYLON.Vector2(u, v);
  26314. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26315. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26316. positions.push(position.x, position.y, position.z);
  26317. normals.push(normal.x, normal.y, normal.z);
  26318. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26319. // And create indices for two triangles.
  26320. var nextI = (i + 1) % stride;
  26321. var nextJ = (j + 1) % stride;
  26322. indices.push(i * stride + j);
  26323. indices.push(i * stride + nextJ);
  26324. indices.push(nextI * stride + j);
  26325. indices.push(i * stride + nextJ);
  26326. indices.push(nextI * stride + nextJ);
  26327. indices.push(nextI * stride + j);
  26328. }
  26329. }
  26330. // Sides
  26331. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26332. // Result
  26333. var vertexData = new VertexData();
  26334. vertexData.indices = indices;
  26335. vertexData.positions = positions;
  26336. vertexData.normals = normals;
  26337. vertexData.uvs = uvs;
  26338. return vertexData;
  26339. };
  26340. /**
  26341. * Creates the VertexData of the LineSystem.
  26342. */
  26343. VertexData.CreateLineSystem = function (options) {
  26344. var indices = [];
  26345. var positions = [];
  26346. var lines = options.lines;
  26347. var idx = 0;
  26348. for (var l = 0; l < lines.length; l++) {
  26349. var points = lines[l];
  26350. for (var index = 0; index < points.length; index++) {
  26351. positions.push(points[index].x, points[index].y, points[index].z);
  26352. if (index > 0) {
  26353. indices.push(idx - 1);
  26354. indices.push(idx);
  26355. }
  26356. idx++;
  26357. }
  26358. }
  26359. var vertexData = new VertexData();
  26360. vertexData.indices = indices;
  26361. vertexData.positions = positions;
  26362. return vertexData;
  26363. };
  26364. /**
  26365. * Create the VertexData of the DashedLines.
  26366. */
  26367. VertexData.CreateDashedLines = function (options) {
  26368. var dashSize = options.dashSize || 3;
  26369. var gapSize = options.gapSize || 1;
  26370. var dashNb = options.dashNb || 200;
  26371. var points = options.points;
  26372. var positions = new Array();
  26373. var indices = new Array();
  26374. var curvect = BABYLON.Vector3.Zero();
  26375. var lg = 0;
  26376. var nb = 0;
  26377. var shft = 0;
  26378. var dashshft = 0;
  26379. var curshft = 0;
  26380. var idx = 0;
  26381. var i = 0;
  26382. for (i = 0; i < points.length - 1; i++) {
  26383. points[i + 1].subtractToRef(points[i], curvect);
  26384. lg += curvect.length();
  26385. }
  26386. shft = lg / dashNb;
  26387. dashshft = dashSize * shft / (dashSize + gapSize);
  26388. for (i = 0; i < points.length - 1; i++) {
  26389. points[i + 1].subtractToRef(points[i], curvect);
  26390. nb = Math.floor(curvect.length() / shft);
  26391. curvect.normalize();
  26392. for (var j = 0; j < nb; j++) {
  26393. curshft = shft * j;
  26394. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26395. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26396. indices.push(idx, idx + 1);
  26397. idx += 2;
  26398. }
  26399. }
  26400. // Result
  26401. var vertexData = new VertexData();
  26402. vertexData.positions = positions;
  26403. vertexData.indices = indices;
  26404. return vertexData;
  26405. };
  26406. /**
  26407. * Creates the VertexData of the Ground.
  26408. */
  26409. VertexData.CreateGround = function (options) {
  26410. var indices = [];
  26411. var positions = [];
  26412. var normals = [];
  26413. var uvs = [];
  26414. var row, col;
  26415. var width = options.width || 1;
  26416. var height = options.height || 1;
  26417. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26418. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26419. for (row = 0; row <= subdivisionsY; row++) {
  26420. for (col = 0; col <= subdivisionsX; col++) {
  26421. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26422. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26423. positions.push(position.x, position.y, position.z);
  26424. normals.push(normal.x, normal.y, normal.z);
  26425. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26426. }
  26427. }
  26428. for (row = 0; row < subdivisionsY; row++) {
  26429. for (col = 0; col < subdivisionsX; col++) {
  26430. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26431. indices.push(col + 1 + row * (subdivisionsX + 1));
  26432. indices.push(col + row * (subdivisionsX + 1));
  26433. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26434. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26435. indices.push(col + row * (subdivisionsX + 1));
  26436. }
  26437. }
  26438. // Result
  26439. var vertexData = new VertexData();
  26440. vertexData.indices = indices;
  26441. vertexData.positions = positions;
  26442. vertexData.normals = normals;
  26443. vertexData.uvs = uvs;
  26444. return vertexData;
  26445. };
  26446. /**
  26447. * Creates the VertexData of the TiledGround.
  26448. */
  26449. VertexData.CreateTiledGround = function (options) {
  26450. var xmin = options.xmin || -1.0;
  26451. var zmin = options.zmin || -1.0;
  26452. var xmax = options.xmax || 1.0;
  26453. var zmax = options.zmax || 1.0;
  26454. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26455. var precision = options.precision || { w: 1, h: 1 };
  26456. var indices = [];
  26457. var positions = [];
  26458. var normals = [];
  26459. var uvs = [];
  26460. var row, col, tileRow, tileCol;
  26461. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26462. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26463. precision.w = (precision.w < 1) ? 1 : precision.w;
  26464. precision.h = (precision.h < 1) ? 1 : precision.h;
  26465. var tileSize = {
  26466. 'w': (xmax - xmin) / subdivisions.w,
  26467. 'h': (zmax - zmin) / subdivisions.h
  26468. };
  26469. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26470. // Indices
  26471. var base = positions.length / 3;
  26472. var rowLength = precision.w + 1;
  26473. for (row = 0; row < precision.h; row++) {
  26474. for (col = 0; col < precision.w; col++) {
  26475. var square = [
  26476. base + col + row * rowLength,
  26477. base + (col + 1) + row * rowLength,
  26478. base + (col + 1) + (row + 1) * rowLength,
  26479. base + col + (row + 1) * rowLength
  26480. ];
  26481. indices.push(square[1]);
  26482. indices.push(square[2]);
  26483. indices.push(square[3]);
  26484. indices.push(square[0]);
  26485. indices.push(square[1]);
  26486. indices.push(square[3]);
  26487. }
  26488. }
  26489. // Position, normals and uvs
  26490. var position = BABYLON.Vector3.Zero();
  26491. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26492. for (row = 0; row <= precision.h; row++) {
  26493. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26494. for (col = 0; col <= precision.w; col++) {
  26495. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26496. position.y = 0;
  26497. positions.push(position.x, position.y, position.z);
  26498. normals.push(normal.x, normal.y, normal.z);
  26499. uvs.push(col / precision.w, row / precision.h);
  26500. }
  26501. }
  26502. }
  26503. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26504. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26505. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26506. }
  26507. }
  26508. // Result
  26509. var vertexData = new VertexData();
  26510. vertexData.indices = indices;
  26511. vertexData.positions = positions;
  26512. vertexData.normals = normals;
  26513. vertexData.uvs = uvs;
  26514. return vertexData;
  26515. };
  26516. /**
  26517. * Creates the VertexData of the Ground designed from a heightmap.
  26518. */
  26519. VertexData.CreateGroundFromHeightMap = function (options) {
  26520. var indices = [];
  26521. var positions = [];
  26522. var normals = [];
  26523. var uvs = [];
  26524. var row, col;
  26525. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26526. // Vertices
  26527. for (row = 0; row <= options.subdivisions; row++) {
  26528. for (col = 0; col <= options.subdivisions; col++) {
  26529. 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));
  26530. // Compute height
  26531. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26532. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26533. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26534. var r = options.buffer[pos] / 255.0;
  26535. var g = options.buffer[pos + 1] / 255.0;
  26536. var b = options.buffer[pos + 2] / 255.0;
  26537. var gradient = r * filter.r + g * filter.g + b * filter.b;
  26538. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26539. // Add vertex
  26540. positions.push(position.x, position.y, position.z);
  26541. normals.push(0, 0, 0);
  26542. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26543. }
  26544. }
  26545. // Indices
  26546. for (row = 0; row < options.subdivisions; row++) {
  26547. for (col = 0; col < options.subdivisions; col++) {
  26548. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26549. indices.push(col + 1 + row * (options.subdivisions + 1));
  26550. indices.push(col + row * (options.subdivisions + 1));
  26551. indices.push(col + (row + 1) * (options.subdivisions + 1));
  26552. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26553. indices.push(col + row * (options.subdivisions + 1));
  26554. }
  26555. }
  26556. // Normals
  26557. VertexData.ComputeNormals(positions, indices, normals);
  26558. // Result
  26559. var vertexData = new VertexData();
  26560. vertexData.indices = indices;
  26561. vertexData.positions = positions;
  26562. vertexData.normals = normals;
  26563. vertexData.uvs = uvs;
  26564. return vertexData;
  26565. };
  26566. /**
  26567. * Creates the VertexData of the Plane.
  26568. */
  26569. VertexData.CreatePlane = function (options) {
  26570. var indices = [];
  26571. var positions = [];
  26572. var normals = [];
  26573. var uvs = [];
  26574. var width = options.width || options.size || 1;
  26575. var height = options.height || options.size || 1;
  26576. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26577. // Vertices
  26578. var halfWidth = width / 2.0;
  26579. var halfHeight = height / 2.0;
  26580. positions.push(-halfWidth, -halfHeight, 0);
  26581. normals.push(0, 0, -1.0);
  26582. uvs.push(0.0, 0.0);
  26583. positions.push(halfWidth, -halfHeight, 0);
  26584. normals.push(0, 0, -1.0);
  26585. uvs.push(1.0, 0.0);
  26586. positions.push(halfWidth, halfHeight, 0);
  26587. normals.push(0, 0, -1.0);
  26588. uvs.push(1.0, 1.0);
  26589. positions.push(-halfWidth, halfHeight, 0);
  26590. normals.push(0, 0, -1.0);
  26591. uvs.push(0.0, 1.0);
  26592. // Indices
  26593. indices.push(0);
  26594. indices.push(1);
  26595. indices.push(2);
  26596. indices.push(0);
  26597. indices.push(2);
  26598. indices.push(3);
  26599. // Sides
  26600. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26601. // Result
  26602. var vertexData = new VertexData();
  26603. vertexData.indices = indices;
  26604. vertexData.positions = positions;
  26605. vertexData.normals = normals;
  26606. vertexData.uvs = uvs;
  26607. return vertexData;
  26608. };
  26609. /**
  26610. * Creates the VertexData of the Disc or regular Polygon.
  26611. */
  26612. VertexData.CreateDisc = function (options) {
  26613. var positions = [];
  26614. var indices = [];
  26615. var normals = [];
  26616. var uvs = [];
  26617. var radius = options.radius || 0.5;
  26618. var tessellation = options.tessellation || 64;
  26619. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26620. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26621. // positions and uvs
  26622. positions.push(0, 0, 0); // disc center first
  26623. uvs.push(0.5, 0.5);
  26624. var theta = Math.PI * 2 * arc;
  26625. var step = theta / tessellation;
  26626. for (var a = 0; a < theta; a += step) {
  26627. var x = Math.cos(a);
  26628. var y = Math.sin(a);
  26629. var u = (x + 1) / 2;
  26630. var v = (1 - y) / 2;
  26631. positions.push(radius * x, radius * y, 0);
  26632. uvs.push(u, v);
  26633. }
  26634. if (arc === 1) {
  26635. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26636. uvs.push(uvs[2], uvs[3]);
  26637. }
  26638. //indices
  26639. var vertexNb = positions.length / 3;
  26640. for (var i = 1; i < vertexNb - 1; i++) {
  26641. indices.push(i + 1, 0, i);
  26642. }
  26643. // result
  26644. VertexData.ComputeNormals(positions, indices, normals);
  26645. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26646. var vertexData = new VertexData();
  26647. vertexData.indices = indices;
  26648. vertexData.positions = positions;
  26649. vertexData.normals = normals;
  26650. vertexData.uvs = uvs;
  26651. return vertexData;
  26652. };
  26653. /**
  26654. * Re-creates the VertexData of the Polygon for sideOrientation.
  26655. */
  26656. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26657. var faceUV = fUV || new Array(3);
  26658. var faceColors = fColors;
  26659. var colors = [];
  26660. // default face colors and UV if undefined
  26661. for (var f = 0; f < 3; f++) {
  26662. if (faceUV[f] === undefined) {
  26663. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26664. }
  26665. if (faceColors && faceColors[f] === undefined) {
  26666. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26667. }
  26668. }
  26669. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26670. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26671. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26672. var indices = polygon.getIndices();
  26673. // set face colours and textures
  26674. var idx = 0;
  26675. var face = 0;
  26676. for (var index = 0; index < normals.length; index += 3) {
  26677. //Edge Face no. 1
  26678. if (Math.abs(normals[index + 1]) == 0) {
  26679. face = 1;
  26680. }
  26681. //Top Face no. 0
  26682. if (normals[index + 1] == 1) {
  26683. face = 0;
  26684. }
  26685. //Bottom Face no. 2
  26686. if (normals[index + 1] == -1) {
  26687. face = 2;
  26688. }
  26689. idx = index / 3;
  26690. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26691. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26692. if (faceColors) {
  26693. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26694. }
  26695. }
  26696. // sides
  26697. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26698. // Result
  26699. var vertexData = new VertexData();
  26700. vertexData.indices = indices;
  26701. vertexData.positions = positions;
  26702. vertexData.normals = normals;
  26703. vertexData.uvs = uvs;
  26704. if (faceColors) {
  26705. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26706. vertexData.colors = totalColors;
  26707. }
  26708. return vertexData;
  26709. };
  26710. /**
  26711. * Creates the VertexData of the IcoSphere.
  26712. */
  26713. VertexData.CreateIcoSphere = function (options) {
  26714. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26715. var radius = options.radius || 1;
  26716. var flat = (options.flat === undefined) ? true : options.flat;
  26717. var subdivisions = options.subdivisions || 4;
  26718. var radiusX = options.radiusX || radius;
  26719. var radiusY = options.radiusY || radius;
  26720. var radiusZ = options.radiusZ || radius;
  26721. var t = (1 + Math.sqrt(5)) / 2;
  26722. // 12 vertex x,y,z
  26723. var ico_vertices = [
  26724. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26725. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26726. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26727. ];
  26728. // index of 3 vertex makes a face of icopshere
  26729. var ico_indices = [
  26730. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26731. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26732. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26733. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26734. ];
  26735. // vertex for uv have aliased position, not for UV
  26736. var vertices_unalias_id = [
  26737. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26738. // vertex alias
  26739. 0,
  26740. 2,
  26741. 3,
  26742. 3,
  26743. 3,
  26744. 4,
  26745. 7,
  26746. 8,
  26747. 9,
  26748. 9,
  26749. 10,
  26750. 11 // 23: B + 12
  26751. ];
  26752. // uv as integer step (not pixels !)
  26753. var ico_vertexuv = [
  26754. 5, 1, 3, 1, 6, 4, 0, 0,
  26755. 5, 3, 4, 2, 2, 2, 4, 0,
  26756. 2, 0, 1, 1, 6, 0, 6, 2,
  26757. // vertex alias (for same vertex on different faces)
  26758. 0, 4,
  26759. 3, 3,
  26760. 4, 4,
  26761. 3, 1,
  26762. 4, 2,
  26763. 4, 4,
  26764. 0, 2,
  26765. 1, 1,
  26766. 2, 2,
  26767. 3, 3,
  26768. 1, 3,
  26769. 2, 4 // 23: B + 12
  26770. ];
  26771. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26772. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26773. // First island of uv mapping
  26774. // v = 4h 3+ 2
  26775. // v = 3h 9+ 4
  26776. // v = 2h 9+ 5 B
  26777. // v = 1h 9 1 0
  26778. // v = 0h 3 8 7 A
  26779. // u = 0 1 2 3 4 5 6 *a
  26780. // Second island of uv mapping
  26781. // v = 4h 0+ B+ 4+
  26782. // v = 3h A+ 2+
  26783. // v = 2h 7+ 6 3+
  26784. // v = 1h 8+ 3+
  26785. // v = 0h
  26786. // u = 0 1 2 3 4 5 6 *a
  26787. // Face layout on texture UV mapping
  26788. // ============
  26789. // \ 4 /\ 16 / ======
  26790. // \ / \ / /\ 11 /
  26791. // \/ 7 \/ / \ /
  26792. // ======= / 10 \/
  26793. // /\ 17 /\ =======
  26794. // / \ / \ \ 15 /\
  26795. // / 8 \/ 12 \ \ / \
  26796. // ============ \/ 6 \
  26797. // \ 18 /\ ============
  26798. // \ / \ \ 5 /\ 0 /
  26799. // \/ 13 \ \ / \ /
  26800. // ======= \/ 1 \/
  26801. // =============
  26802. // /\ 19 /\ 2 /\
  26803. // / \ / \ / \
  26804. // / 14 \/ 9 \/ 3 \
  26805. // ===================
  26806. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26807. var ustep = 138 / 1024;
  26808. var vstep = 239 / 1024;
  26809. var uoffset = 60 / 1024;
  26810. var voffset = 26 / 1024;
  26811. // Second island should have margin, not to touch the first island
  26812. // avoid any borderline artefact in pixel rounding
  26813. var island_u_offset = -40 / 1024;
  26814. var island_v_offset = +20 / 1024;
  26815. // face is either island 0 or 1 :
  26816. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26817. var island = [
  26818. 0, 0, 0, 0, 1,
  26819. 0, 0, 1, 1, 0,
  26820. 0, 0, 1, 1, 0,
  26821. 0, 1, 1, 1, 0 // 15 - 19
  26822. ];
  26823. var indices = [];
  26824. var positions = [];
  26825. var normals = [];
  26826. var uvs = [];
  26827. var current_indice = 0;
  26828. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26829. var face_vertex_pos = new Array(3);
  26830. var face_vertex_uv = new Array(3);
  26831. var v012;
  26832. for (v012 = 0; v012 < 3; v012++) {
  26833. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26834. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26835. }
  26836. // create all with normals
  26837. for (var face = 0; face < 20; face++) {
  26838. // 3 vertex per face
  26839. for (v012 = 0; v012 < 3; v012++) {
  26840. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26841. var v_id = ico_indices[3 * face + v012];
  26842. // vertex have 3D position (x,y,z)
  26843. 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]);
  26844. // Normalize to get normal, then scale to radius
  26845. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26846. // uv Coordinates from vertex ID
  26847. 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);
  26848. }
  26849. // Subdivide the face (interpolate pos, norm, uv)
  26850. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26851. // - norm is linear interpolation of vertex corner normal
  26852. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26853. // - uv is linear interpolation
  26854. //
  26855. // Topology is as below for sub-divide by 2
  26856. // vertex shown as v0,v1,v2
  26857. // interp index is i1 to progress in range [v0,v1[
  26858. // interp index is i2 to progress in range [v0,v2[
  26859. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26860. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26861. //
  26862. //
  26863. // i2 v2
  26864. // ^ ^
  26865. // / / \
  26866. // / / \
  26867. // / / \
  26868. // / / (0,1) \
  26869. // / #---------\
  26870. // / / \ (0,0)'/ \
  26871. // / / \ / \
  26872. // / / \ / \
  26873. // / / (0,0) \ / (1,0) \
  26874. // / #---------#---------\
  26875. // v0 v1
  26876. //
  26877. // --------------------> i1
  26878. //
  26879. // interp of (i1,i2):
  26880. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26881. // along i1 : lerp(x0,x1, i1/(S-i2))
  26882. //
  26883. // centroid of triangle is needed to get help normal computation
  26884. // (c1,c2) are used for centroid location
  26885. var interp_vertex = function (i1, i2, c1, c2) {
  26886. // vertex is interpolated from
  26887. // - face_vertex_pos[0..2]
  26888. // - face_vertex_uv[0..2]
  26889. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26890. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26891. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26892. pos_interp.normalize();
  26893. var vertex_normal;
  26894. if (flat) {
  26895. // in flat mode, recalculate normal as face centroid normal
  26896. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26897. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26898. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26899. }
  26900. else {
  26901. // in smooth mode, recalculate normal from each single vertex position
  26902. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26903. }
  26904. // Vertex normal need correction due to X,Y,Z radius scaling
  26905. vertex_normal.x /= radiusX;
  26906. vertex_normal.y /= radiusY;
  26907. vertex_normal.z /= radiusZ;
  26908. vertex_normal.normalize();
  26909. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26910. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26911. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26912. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26913. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26914. uvs.push(uv_interp.x, uv_interp.y);
  26915. // push each vertex has member of a face
  26916. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26917. indices.push(current_indice);
  26918. current_indice++;
  26919. };
  26920. for (var i2 = 0; i2 < subdivisions; i2++) {
  26921. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26922. // face : (i1,i2) for /\ :
  26923. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26924. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26925. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26926. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26927. if (i1 + i2 + 1 < subdivisions) {
  26928. // face : (i1,i2)' for \/ :
  26929. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26930. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26931. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26932. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26933. }
  26934. }
  26935. }
  26936. }
  26937. // Sides
  26938. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26939. // Result
  26940. var vertexData = new VertexData();
  26941. vertexData.indices = indices;
  26942. vertexData.positions = positions;
  26943. vertexData.normals = normals;
  26944. vertexData.uvs = uvs;
  26945. return vertexData;
  26946. };
  26947. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26948. /**
  26949. * Creates the VertexData of the Polyhedron.
  26950. */
  26951. VertexData.CreatePolyhedron = function (options) {
  26952. // provided polyhedron types :
  26953. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26954. // 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)
  26955. var polyhedra = [];
  26956. 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]] };
  26957. 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]] };
  26958. polyhedra[2] = {
  26959. 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]],
  26960. 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]]
  26961. };
  26962. polyhedra[3] = {
  26963. 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]],
  26964. 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]]
  26965. };
  26966. polyhedra[4] = {
  26967. 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]],
  26968. 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]]
  26969. };
  26970. 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]] };
  26971. 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]] };
  26972. 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]] };
  26973. 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]] };
  26974. 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]] };
  26975. 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]] };
  26976. 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]] };
  26977. 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]] };
  26978. 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]] };
  26979. polyhedra[14] = {
  26980. 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]],
  26981. 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]]
  26982. };
  26983. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26984. var size = options.size;
  26985. var sizeX = options.sizeX || size || 1;
  26986. var sizeY = options.sizeY || size || 1;
  26987. var sizeZ = options.sizeZ || size || 1;
  26988. var data = options.custom || polyhedra[type];
  26989. var nbfaces = data.face.length;
  26990. var faceUV = options.faceUV || new Array(nbfaces);
  26991. var faceColors = options.faceColors;
  26992. var flat = (options.flat === undefined) ? true : options.flat;
  26993. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26994. var positions = [];
  26995. var indices = [];
  26996. var normals = [];
  26997. var uvs = [];
  26998. var colors = [];
  26999. var index = 0;
  27000. var faceIdx = 0; // face cursor in the array "indexes"
  27001. var indexes = [];
  27002. var i = 0;
  27003. var f = 0;
  27004. var u, v, ang, x, y, tmp;
  27005. // default face colors and UV if undefined
  27006. if (flat) {
  27007. for (f = 0; f < nbfaces; f++) {
  27008. if (faceColors && faceColors[f] === undefined) {
  27009. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27010. }
  27011. if (faceUV && faceUV[f] === undefined) {
  27012. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27013. }
  27014. }
  27015. }
  27016. if (!flat) {
  27017. for (i = 0; i < data.vertex.length; i++) {
  27018. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27019. uvs.push(0, 0);
  27020. }
  27021. for (f = 0; f < nbfaces; f++) {
  27022. for (i = 0; i < data.face[f].length - 2; i++) {
  27023. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27024. }
  27025. }
  27026. }
  27027. else {
  27028. for (f = 0; f < nbfaces; f++) {
  27029. var fl = data.face[f].length; // number of vertices of the current face
  27030. ang = 2 * Math.PI / fl;
  27031. x = 0.5 * Math.tan(ang / 2);
  27032. y = 0.5;
  27033. // positions, uvs, colors
  27034. for (i = 0; i < fl; i++) {
  27035. // positions
  27036. 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);
  27037. indexes.push(index);
  27038. index++;
  27039. // uvs
  27040. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27041. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27042. uvs.push(u, v);
  27043. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27044. y = x * Math.sin(ang) + y * Math.cos(ang);
  27045. x = tmp;
  27046. // colors
  27047. if (faceColors) {
  27048. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27049. }
  27050. }
  27051. // indices from indexes
  27052. for (i = 0; i < fl - 2; i++) {
  27053. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27054. }
  27055. faceIdx += fl;
  27056. }
  27057. }
  27058. VertexData.ComputeNormals(positions, indices, normals);
  27059. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27060. var vertexData = new VertexData();
  27061. vertexData.positions = positions;
  27062. vertexData.indices = indices;
  27063. vertexData.normals = normals;
  27064. vertexData.uvs = uvs;
  27065. if (faceColors && flat) {
  27066. vertexData.colors = colors;
  27067. }
  27068. return vertexData;
  27069. };
  27070. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27071. /**
  27072. * Creates the VertexData of the Torus Knot.
  27073. */
  27074. VertexData.CreateTorusKnot = function (options) {
  27075. var indices = [];
  27076. var positions = [];
  27077. var normals = [];
  27078. var uvs = [];
  27079. var radius = options.radius || 2;
  27080. var tube = options.tube || 0.5;
  27081. var radialSegments = options.radialSegments || 32;
  27082. var tubularSegments = options.tubularSegments || 32;
  27083. var p = options.p || 2;
  27084. var q = options.q || 3;
  27085. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27086. // Helper
  27087. var getPos = function (angle) {
  27088. var cu = Math.cos(angle);
  27089. var su = Math.sin(angle);
  27090. var quOverP = q / p * angle;
  27091. var cs = Math.cos(quOverP);
  27092. var tx = radius * (2 + cs) * 0.5 * cu;
  27093. var ty = radius * (2 + cs) * su * 0.5;
  27094. var tz = radius * Math.sin(quOverP) * 0.5;
  27095. return new BABYLON.Vector3(tx, ty, tz);
  27096. };
  27097. // Vertices
  27098. var i;
  27099. var j;
  27100. for (i = 0; i <= radialSegments; i++) {
  27101. var modI = i % radialSegments;
  27102. var u = modI / radialSegments * 2 * p * Math.PI;
  27103. var p1 = getPos(u);
  27104. var p2 = getPos(u + 0.01);
  27105. var tang = p2.subtract(p1);
  27106. var n = p2.add(p1);
  27107. var bitan = BABYLON.Vector3.Cross(tang, n);
  27108. n = BABYLON.Vector3.Cross(bitan, tang);
  27109. bitan.normalize();
  27110. n.normalize();
  27111. for (j = 0; j < tubularSegments; j++) {
  27112. var modJ = j % tubularSegments;
  27113. var v = modJ / tubularSegments * 2 * Math.PI;
  27114. var cx = -tube * Math.cos(v);
  27115. var cy = tube * Math.sin(v);
  27116. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27117. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27118. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27119. uvs.push(i / radialSegments);
  27120. uvs.push(j / tubularSegments);
  27121. }
  27122. }
  27123. for (i = 0; i < radialSegments; i++) {
  27124. for (j = 0; j < tubularSegments; j++) {
  27125. var jNext = (j + 1) % tubularSegments;
  27126. var a = i * tubularSegments + j;
  27127. var b = (i + 1) * tubularSegments + j;
  27128. var c = (i + 1) * tubularSegments + jNext;
  27129. var d = i * tubularSegments + jNext;
  27130. indices.push(d);
  27131. indices.push(b);
  27132. indices.push(a);
  27133. indices.push(d);
  27134. indices.push(c);
  27135. indices.push(b);
  27136. }
  27137. }
  27138. // Normals
  27139. VertexData.ComputeNormals(positions, indices, normals);
  27140. // Sides
  27141. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27142. // Result
  27143. var vertexData = new VertexData();
  27144. vertexData.indices = indices;
  27145. vertexData.positions = positions;
  27146. vertexData.normals = normals;
  27147. vertexData.uvs = uvs;
  27148. return vertexData;
  27149. };
  27150. // Tools
  27151. /**
  27152. * @param {any} - positions (number[] or Float32Array)
  27153. * @param {any} - indices (number[] or Uint16Array)
  27154. * @param {any} - normals (number[] or Float32Array)
  27155. * options (optional) :
  27156. * facetPositions : optional array of facet positions (vector3)
  27157. * facetNormals : optional array of facet normals (vector3)
  27158. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  27159. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  27160. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  27161. * bbSize : optional bounding box size data, required for facetPartitioning computation
  27162. * bInfo : optional bounding info, required for facetPartitioning computation
  27163. */
  27164. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  27165. // temporary scalar variables
  27166. var index = 0; // facet index
  27167. var p1p2x = 0.0; // p1p2 vector x coordinate
  27168. var p1p2y = 0.0; // p1p2 vector y coordinate
  27169. var p1p2z = 0.0; // p1p2 vector z coordinate
  27170. var p3p2x = 0.0; // p3p2 vector x coordinate
  27171. var p3p2y = 0.0; // p3p2 vector y coordinate
  27172. var p3p2z = 0.0; // p3p2 vector z coordinate
  27173. var faceNormalx = 0.0; // facet normal x coordinate
  27174. var faceNormaly = 0.0; // facet normal y coordinate
  27175. var faceNormalz = 0.0; // facet normal z coordinate
  27176. var length = 0.0; // facet normal length before normalization
  27177. var v1x = 0; // vector1 x index in the positions array
  27178. var v1y = 0; // vector1 y index in the positions array
  27179. var v1z = 0; // vector1 z index in the positions array
  27180. var v2x = 0; // vector2 x index in the positions array
  27181. var v2y = 0; // vector2 y index in the positions array
  27182. var v2z = 0; // vector2 z index in the positions array
  27183. var v3x = 0; // vector3 x index in the positions array
  27184. var v3y = 0; // vector3 y index in the positions array
  27185. var v3z = 0; // vector3 z index in the positions array
  27186. var computeFacetNormals = false;
  27187. var computeFacetPositions = false;
  27188. var computeFacetPartitioning = false;
  27189. var faceNormalSign = 1;
  27190. if (options) {
  27191. computeFacetNormals = (options.facetNormals) ? true : false;
  27192. computeFacetPositions = (options.facetPositions) ? true : false;
  27193. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  27194. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  27195. }
  27196. // facetPartitioning reinit if needed
  27197. if (computeFacetPartitioning) {
  27198. var ox = 0; // X partitioning index for facet position
  27199. var oy = 0; // Y partinioning index for facet position
  27200. var oz = 0; // Z partinioning index for facet position
  27201. var b1x = 0; // X partitioning index for facet v1 vertex
  27202. var b1y = 0; // Y partitioning index for facet v1 vertex
  27203. var b1z = 0; // z partitioning index for facet v1 vertex
  27204. var b2x = 0; // X partitioning index for facet v2 vertex
  27205. var b2y = 0; // Y partitioning index for facet v2 vertex
  27206. var b2z = 0; // Z partitioning index for facet v2 vertex
  27207. var b3x = 0; // X partitioning index for facet v3 vertex
  27208. var b3y = 0; // Y partitioning index for facet v3 vertex
  27209. var b3z = 0; // Z partitioning index for facet v3 vertex
  27210. var block_idx_o = 0; // facet barycenter block index
  27211. var block_idx_v1 = 0; // v1 vertex block index
  27212. var block_idx_v2 = 0; // v2 vertex block index
  27213. var block_idx_v3 = 0; // v3 vertex block index
  27214. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  27215. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  27216. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  27217. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  27218. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  27219. var subSq = options.subDiv.max * options.subDiv.max;
  27220. options.facetPartitioning.length = 0;
  27221. }
  27222. // reset the normals
  27223. for (index = 0; index < positions.length; index++) {
  27224. normals[index] = 0.0;
  27225. }
  27226. // Loop : 1 indice triplet = 1 facet
  27227. var nbFaces = indices.length / 3;
  27228. for (index = 0; index < nbFaces; index++) {
  27229. // get the indexes of the coordinates of each vertex of the facet
  27230. v1x = indices[index * 3] * 3;
  27231. v1y = v1x + 1;
  27232. v1z = v1x + 2;
  27233. v2x = indices[index * 3 + 1] * 3;
  27234. v2y = v2x + 1;
  27235. v2z = v2x + 2;
  27236. v3x = indices[index * 3 + 2] * 3;
  27237. v3y = v3x + 1;
  27238. v3z = v3x + 2;
  27239. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  27240. p1p2y = positions[v1y] - positions[v2y];
  27241. p1p2z = positions[v1z] - positions[v2z];
  27242. p3p2x = positions[v3x] - positions[v2x];
  27243. p3p2y = positions[v3y] - positions[v2y];
  27244. p3p2z = positions[v3z] - positions[v2z];
  27245. // compute the face normal with the cross product
  27246. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  27247. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  27248. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  27249. // normalize this normal and store it in the array facetData
  27250. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27251. length = (length === 0) ? 1.0 : length;
  27252. faceNormalx /= length;
  27253. faceNormaly /= length;
  27254. faceNormalz /= length;
  27255. if (computeFacetNormals) {
  27256. options.facetNormals[index].x = faceNormalx;
  27257. options.facetNormals[index].y = faceNormaly;
  27258. options.facetNormals[index].z = faceNormalz;
  27259. }
  27260. if (computeFacetPositions) {
  27261. // compute and the facet barycenter coordinates in the array facetPositions
  27262. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  27263. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  27264. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  27265. }
  27266. if (computeFacetPartitioning) {
  27267. // store the facet indexes in arrays in the main facetPartitioning array :
  27268. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  27269. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27270. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27271. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27272. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27273. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27274. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27275. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27276. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27277. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27278. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27279. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27280. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27281. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  27282. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  27283. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  27284. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  27285. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  27286. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  27287. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  27288. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  27289. // push each facet index in each block containing the vertex
  27290. options.facetPartitioning[block_idx_v1].push(index);
  27291. if (block_idx_v2 != block_idx_v1) {
  27292. options.facetPartitioning[block_idx_v2].push(index);
  27293. }
  27294. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  27295. options.facetPartitioning[block_idx_v3].push(index);
  27296. }
  27297. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  27298. options.facetPartitioning[block_idx_o].push(index);
  27299. }
  27300. }
  27301. // compute the normals anyway
  27302. normals[v1x] += faceNormalx; // accumulate all the normals per face
  27303. normals[v1y] += faceNormaly;
  27304. normals[v1z] += faceNormalz;
  27305. normals[v2x] += faceNormalx;
  27306. normals[v2y] += faceNormaly;
  27307. normals[v2z] += faceNormalz;
  27308. normals[v3x] += faceNormalx;
  27309. normals[v3y] += faceNormaly;
  27310. normals[v3z] += faceNormalz;
  27311. }
  27312. // last normalization of each normal
  27313. for (index = 0; index < normals.length / 3; index++) {
  27314. faceNormalx = normals[index * 3];
  27315. faceNormaly = normals[index * 3 + 1];
  27316. faceNormalz = normals[index * 3 + 2];
  27317. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27318. length = (length === 0) ? 1.0 : length;
  27319. faceNormalx /= length;
  27320. faceNormaly /= length;
  27321. faceNormalz /= length;
  27322. normals[index * 3] = faceNormalx;
  27323. normals[index * 3 + 1] = faceNormaly;
  27324. normals[index * 3 + 2] = faceNormalz;
  27325. }
  27326. };
  27327. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  27328. var li = indices.length;
  27329. var ln = normals.length;
  27330. var i;
  27331. var n;
  27332. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27333. switch (sideOrientation) {
  27334. case BABYLON.Mesh.FRONTSIDE:
  27335. // nothing changed
  27336. break;
  27337. case BABYLON.Mesh.BACKSIDE:
  27338. var tmp;
  27339. // indices
  27340. for (i = 0; i < li; i += 3) {
  27341. tmp = indices[i];
  27342. indices[i] = indices[i + 2];
  27343. indices[i + 2] = tmp;
  27344. }
  27345. // normals
  27346. for (n = 0; n < ln; n++) {
  27347. normals[n] = -normals[n];
  27348. }
  27349. break;
  27350. case BABYLON.Mesh.DOUBLESIDE:
  27351. // positions
  27352. var lp = positions.length;
  27353. var l = lp / 3;
  27354. for (var p = 0; p < lp; p++) {
  27355. positions[lp + p] = positions[p];
  27356. }
  27357. // indices
  27358. for (i = 0; i < li; i += 3) {
  27359. indices[i + li] = indices[i + 2] + l;
  27360. indices[i + 1 + li] = indices[i + 1] + l;
  27361. indices[i + 2 + li] = indices[i] + l;
  27362. }
  27363. // normals
  27364. for (n = 0; n < ln; n++) {
  27365. normals[ln + n] = -normals[n];
  27366. }
  27367. // uvs
  27368. var lu = uvs.length;
  27369. var u = 0;
  27370. for (u = 0; u < lu; u++) {
  27371. uvs[u + lu] = uvs[u];
  27372. }
  27373. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27374. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27375. u = 0;
  27376. for (i = 0; i < lu / 2; i++) {
  27377. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  27378. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  27379. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  27380. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  27381. u += 2;
  27382. }
  27383. break;
  27384. }
  27385. };
  27386. /**
  27387. * Creates a new VertexData from the imported parameters.
  27388. */
  27389. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27390. var vertexData = new VertexData();
  27391. // positions
  27392. var positions = parsedVertexData.positions;
  27393. if (positions) {
  27394. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27395. }
  27396. // normals
  27397. var normals = parsedVertexData.normals;
  27398. if (normals) {
  27399. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27400. }
  27401. // tangents
  27402. var tangents = parsedVertexData.tangents;
  27403. if (tangents) {
  27404. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27405. }
  27406. // uvs
  27407. var uvs = parsedVertexData.uvs;
  27408. if (uvs) {
  27409. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27410. }
  27411. // uv2s
  27412. var uv2s = parsedVertexData.uv2s;
  27413. if (uv2s) {
  27414. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27415. }
  27416. // uv3s
  27417. var uv3s = parsedVertexData.uv3s;
  27418. if (uv3s) {
  27419. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27420. }
  27421. // uv4s
  27422. var uv4s = parsedVertexData.uv4s;
  27423. if (uv4s) {
  27424. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27425. }
  27426. // uv5s
  27427. var uv5s = parsedVertexData.uv5s;
  27428. if (uv5s) {
  27429. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27430. }
  27431. // uv6s
  27432. var uv6s = parsedVertexData.uv6s;
  27433. if (uv6s) {
  27434. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27435. }
  27436. // colors
  27437. var colors = parsedVertexData.colors;
  27438. if (colors) {
  27439. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27440. }
  27441. // matricesIndices
  27442. var matricesIndices = parsedVertexData.matricesIndices;
  27443. if (matricesIndices) {
  27444. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27445. }
  27446. // matricesWeights
  27447. var matricesWeights = parsedVertexData.matricesWeights;
  27448. if (matricesWeights) {
  27449. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27450. }
  27451. // indices
  27452. var indices = parsedVertexData.indices;
  27453. if (indices) {
  27454. vertexData.indices = indices;
  27455. }
  27456. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27457. };
  27458. return VertexData;
  27459. }());
  27460. BABYLON.VertexData = VertexData;
  27461. })(BABYLON || (BABYLON = {}));
  27462. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27463. var BABYLON;
  27464. (function (BABYLON) {
  27465. var Geometry = (function () {
  27466. function Geometry(id, scene, vertexData, updatable, mesh) {
  27467. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27468. this._totalVertices = 0;
  27469. this._isDisposed = false;
  27470. this.id = id;
  27471. this._engine = scene.getEngine();
  27472. this._meshes = [];
  27473. this._scene = scene;
  27474. //Init vertex buffer cache
  27475. this._vertexBuffers = {};
  27476. this._indices = [];
  27477. // vertexData
  27478. if (vertexData) {
  27479. this.setAllVerticesData(vertexData, updatable);
  27480. }
  27481. else {
  27482. this._totalVertices = 0;
  27483. this._indices = [];
  27484. }
  27485. if (this._engine.getCaps().vertexArrayObject) {
  27486. this._vertexArrayObjects = {};
  27487. }
  27488. // applyToMesh
  27489. if (mesh) {
  27490. if (mesh.getClassName() === "LinesMesh") {
  27491. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  27492. this.updateExtend();
  27493. }
  27494. this.applyToMesh(mesh);
  27495. mesh.computeWorldMatrix(true);
  27496. }
  27497. }
  27498. Object.defineProperty(Geometry.prototype, "boundingBias", {
  27499. /**
  27500. * 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
  27501. * @returns The Bias Vector
  27502. */
  27503. get: function () {
  27504. return this._boundingBias;
  27505. },
  27506. set: function (value) {
  27507. if (this._boundingBias && this._boundingBias.equals(value)) {
  27508. return;
  27509. }
  27510. this._boundingBias = value.clone();
  27511. this.updateBoundingInfo(true, null);
  27512. },
  27513. enumerable: true,
  27514. configurable: true
  27515. });
  27516. Object.defineProperty(Geometry.prototype, "extend", {
  27517. get: function () {
  27518. return this._extend;
  27519. },
  27520. enumerable: true,
  27521. configurable: true
  27522. });
  27523. Geometry.prototype.getScene = function () {
  27524. return this._scene;
  27525. };
  27526. Geometry.prototype.getEngine = function () {
  27527. return this._engine;
  27528. };
  27529. Geometry.prototype.isReady = function () {
  27530. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27531. };
  27532. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  27533. get: function () {
  27534. for (var index = 0; index < this._meshes.length; index++) {
  27535. if (!this._meshes[index].doNotSerialize) {
  27536. return false;
  27537. }
  27538. }
  27539. return true;
  27540. },
  27541. enumerable: true,
  27542. configurable: true
  27543. });
  27544. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27545. vertexData.applyToGeometry(this, updatable);
  27546. this.notifyUpdate();
  27547. };
  27548. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27549. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27550. this.setVerticesBuffer(buffer);
  27551. };
  27552. Geometry.prototype.removeVerticesData = function (kind) {
  27553. if (this._vertexBuffers[kind]) {
  27554. this._vertexBuffers[kind].dispose();
  27555. delete this._vertexBuffers[kind];
  27556. }
  27557. };
  27558. Geometry.prototype.setVerticesBuffer = function (buffer) {
  27559. var kind = buffer.getKind();
  27560. if (this._vertexBuffers[kind]) {
  27561. this._vertexBuffers[kind].dispose();
  27562. }
  27563. this._vertexBuffers[kind] = buffer;
  27564. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27565. var data = buffer.getData();
  27566. var stride = buffer.getStrideSize();
  27567. this._totalVertices = data.length / stride;
  27568. this.updateExtend(data, stride);
  27569. this._resetPointsArrayCache();
  27570. var meshes = this._meshes;
  27571. var numOfMeshes = meshes.length;
  27572. for (var index = 0; index < numOfMeshes; index++) {
  27573. var mesh = meshes[index];
  27574. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27575. mesh._createGlobalSubMesh();
  27576. mesh.computeWorldMatrix(true);
  27577. }
  27578. }
  27579. this.notifyUpdate(kind);
  27580. if (this._vertexArrayObjects) {
  27581. this._disposeVertexArrayObjects();
  27582. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  27583. }
  27584. };
  27585. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27586. var vertexBuffer = this.getVertexBuffer(kind);
  27587. if (!vertexBuffer) {
  27588. return;
  27589. }
  27590. vertexBuffer.updateDirectly(data, offset);
  27591. this.notifyUpdate(kind);
  27592. };
  27593. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27594. var vertexBuffer = this.getVertexBuffer(kind);
  27595. if (!vertexBuffer) {
  27596. return;
  27597. }
  27598. vertexBuffer.update(data);
  27599. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27600. var stride = vertexBuffer.getStrideSize();
  27601. this._totalVertices = data.length / stride;
  27602. this.updateBoundingInfo(updateExtends, data);
  27603. }
  27604. this.notifyUpdate(kind);
  27605. };
  27606. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27607. if (updateExtends) {
  27608. this.updateExtend(data);
  27609. }
  27610. var meshes = this._meshes;
  27611. var numOfMeshes = meshes.length;
  27612. this._resetPointsArrayCache();
  27613. for (var index = 0; index < numOfMeshes; index++) {
  27614. var mesh = meshes[index];
  27615. if (updateExtends) {
  27616. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27617. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27618. var subMesh = mesh.subMeshes[subIndex];
  27619. subMesh.refreshBoundingInfo();
  27620. }
  27621. }
  27622. }
  27623. };
  27624. Geometry.prototype._bind = function (effect, indexToBind) {
  27625. if (indexToBind === void 0) { indexToBind = undefined; }
  27626. if (indexToBind === undefined) {
  27627. indexToBind = this._indexBuffer;
  27628. }
  27629. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27630. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27631. return;
  27632. }
  27633. // Using VAO
  27634. if (!this._vertexArrayObjects[effect.key]) {
  27635. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27636. }
  27637. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27638. };
  27639. Geometry.prototype.getTotalVertices = function () {
  27640. if (!this.isReady()) {
  27641. return 0;
  27642. }
  27643. return this._totalVertices;
  27644. };
  27645. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27646. var vertexBuffer = this.getVertexBuffer(kind);
  27647. if (!vertexBuffer) {
  27648. return null;
  27649. }
  27650. var orig = vertexBuffer.getData();
  27651. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27652. return orig;
  27653. }
  27654. else {
  27655. var len = orig.length;
  27656. var copy = [];
  27657. for (var i = 0; i < len; i++) {
  27658. copy.push(orig[i]);
  27659. }
  27660. return copy;
  27661. }
  27662. };
  27663. Geometry.prototype.getVertexBuffer = function (kind) {
  27664. if (!this.isReady()) {
  27665. return null;
  27666. }
  27667. return this._vertexBuffers[kind];
  27668. };
  27669. Geometry.prototype.getVertexBuffers = function () {
  27670. if (!this.isReady()) {
  27671. return null;
  27672. }
  27673. return this._vertexBuffers;
  27674. };
  27675. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27676. if (!this._vertexBuffers) {
  27677. if (this._delayInfo) {
  27678. return this._delayInfo.indexOf(kind) !== -1;
  27679. }
  27680. return false;
  27681. }
  27682. return this._vertexBuffers[kind] !== undefined;
  27683. };
  27684. Geometry.prototype.getVerticesDataKinds = function () {
  27685. var result = [];
  27686. var kind;
  27687. if (!this._vertexBuffers && this._delayInfo) {
  27688. for (kind in this._delayInfo) {
  27689. result.push(kind);
  27690. }
  27691. }
  27692. else {
  27693. for (kind in this._vertexBuffers) {
  27694. result.push(kind);
  27695. }
  27696. }
  27697. return result;
  27698. };
  27699. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27700. if (this._indexBuffer) {
  27701. this._engine._releaseBuffer(this._indexBuffer);
  27702. }
  27703. this._disposeVertexArrayObjects();
  27704. this._indices = indices;
  27705. if (this._meshes.length !== 0 && this._indices) {
  27706. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27707. }
  27708. if (totalVertices !== undefined) {
  27709. this._totalVertices = totalVertices;
  27710. }
  27711. var meshes = this._meshes;
  27712. var numOfMeshes = meshes.length;
  27713. for (var index = 0; index < numOfMeshes; index++) {
  27714. meshes[index]._createGlobalSubMesh();
  27715. }
  27716. this.notifyUpdate();
  27717. };
  27718. Geometry.prototype.getTotalIndices = function () {
  27719. if (!this.isReady()) {
  27720. return 0;
  27721. }
  27722. return this._indices.length;
  27723. };
  27724. Geometry.prototype.getIndices = function (copyWhenShared) {
  27725. if (!this.isReady()) {
  27726. return null;
  27727. }
  27728. var orig = this._indices;
  27729. if (!copyWhenShared || this._meshes.length === 1) {
  27730. return orig;
  27731. }
  27732. else {
  27733. var len = orig.length;
  27734. var copy = [];
  27735. for (var i = 0; i < len; i++) {
  27736. copy.push(orig[i]);
  27737. }
  27738. return copy;
  27739. }
  27740. };
  27741. Geometry.prototype.getIndexBuffer = function () {
  27742. if (!this.isReady()) {
  27743. return null;
  27744. }
  27745. return this._indexBuffer;
  27746. };
  27747. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27748. if (!effect || !this._vertexArrayObjects) {
  27749. return;
  27750. }
  27751. if (this._vertexArrayObjects[effect.key]) {
  27752. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27753. delete this._vertexArrayObjects[effect.key];
  27754. }
  27755. };
  27756. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27757. var meshes = this._meshes;
  27758. var index = meshes.indexOf(mesh);
  27759. if (index === -1) {
  27760. return;
  27761. }
  27762. meshes.splice(index, 1);
  27763. mesh._geometry = null;
  27764. if (meshes.length === 0 && shouldDispose) {
  27765. this.dispose();
  27766. }
  27767. };
  27768. Geometry.prototype.applyToMesh = function (mesh) {
  27769. if (mesh._geometry === this) {
  27770. return;
  27771. }
  27772. var previousGeometry = mesh._geometry;
  27773. if (previousGeometry) {
  27774. previousGeometry.releaseForMesh(mesh);
  27775. }
  27776. var meshes = this._meshes;
  27777. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27778. mesh._geometry = this;
  27779. this._scene.pushGeometry(this);
  27780. meshes.push(mesh);
  27781. if (this.isReady()) {
  27782. this._applyToMesh(mesh);
  27783. }
  27784. else {
  27785. mesh._boundingInfo = this._boundingInfo;
  27786. }
  27787. };
  27788. Geometry.prototype.updateExtend = function (data, stride) {
  27789. if (data === void 0) { data = null; }
  27790. if (!data) {
  27791. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27792. }
  27793. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27794. };
  27795. Geometry.prototype._applyToMesh = function (mesh) {
  27796. var numOfMeshes = this._meshes.length;
  27797. // vertexBuffers
  27798. for (var kind in this._vertexBuffers) {
  27799. if (numOfMeshes === 1) {
  27800. this._vertexBuffers[kind].create();
  27801. }
  27802. var buffer = this._vertexBuffers[kind].getBuffer();
  27803. if (buffer)
  27804. buffer.references = numOfMeshes;
  27805. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27806. if (!this._extend) {
  27807. this.updateExtend(this._vertexBuffers[kind].getData());
  27808. }
  27809. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27810. mesh._createGlobalSubMesh();
  27811. //bounding info was just created again, world matrix should be applied again.
  27812. mesh._updateBoundingInfo();
  27813. }
  27814. }
  27815. // indexBuffer
  27816. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27817. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27818. }
  27819. if (this._indexBuffer) {
  27820. this._indexBuffer.references = numOfMeshes;
  27821. }
  27822. };
  27823. Geometry.prototype.notifyUpdate = function (kind) {
  27824. if (this.onGeometryUpdated) {
  27825. this.onGeometryUpdated(this, kind);
  27826. }
  27827. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27828. var mesh = _a[_i];
  27829. mesh._markSubMeshesAsAttributesDirty();
  27830. }
  27831. };
  27832. Geometry.prototype.load = function (scene, onLoaded) {
  27833. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27834. return;
  27835. }
  27836. if (this.isReady()) {
  27837. if (onLoaded) {
  27838. onLoaded();
  27839. }
  27840. return;
  27841. }
  27842. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27843. this._queueLoad(scene, onLoaded);
  27844. };
  27845. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27846. var _this = this;
  27847. scene._addPendingData(this);
  27848. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27849. _this._delayLoadingFunction(JSON.parse(data), _this);
  27850. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27851. _this._delayInfo = [];
  27852. scene._removePendingData(_this);
  27853. var meshes = _this._meshes;
  27854. var numOfMeshes = meshes.length;
  27855. for (var index = 0; index < numOfMeshes; index++) {
  27856. _this._applyToMesh(meshes[index]);
  27857. }
  27858. if (onLoaded) {
  27859. onLoaded();
  27860. }
  27861. }, function () { }, scene.database);
  27862. };
  27863. /**
  27864. * Invert the geometry to move from a right handed system to a left handed one.
  27865. */
  27866. Geometry.prototype.toLeftHanded = function () {
  27867. // Flip faces
  27868. var tIndices = this.getIndices(false);
  27869. if (tIndices != null && tIndices.length > 0) {
  27870. for (var i = 0; i < tIndices.length; i += 3) {
  27871. var tTemp = tIndices[i + 0];
  27872. tIndices[i + 0] = tIndices[i + 2];
  27873. tIndices[i + 2] = tTemp;
  27874. }
  27875. this.setIndices(tIndices);
  27876. }
  27877. // Negate position.z
  27878. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27879. if (tPositions != null && tPositions.length > 0) {
  27880. for (var i = 0; i < tPositions.length; i += 3) {
  27881. tPositions[i + 2] = -tPositions[i + 2];
  27882. }
  27883. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27884. }
  27885. // Negate normal.z
  27886. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27887. if (tNormals != null && tNormals.length > 0) {
  27888. for (var i = 0; i < tNormals.length; i += 3) {
  27889. tNormals[i + 2] = -tNormals[i + 2];
  27890. }
  27891. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27892. }
  27893. };
  27894. // Cache
  27895. Geometry.prototype._resetPointsArrayCache = function () {
  27896. this._positions = null;
  27897. };
  27898. Geometry.prototype._generatePointsArray = function () {
  27899. if (this._positions)
  27900. return true;
  27901. this._positions = [];
  27902. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27903. if (!data) {
  27904. return false;
  27905. }
  27906. for (var index = 0; index < data.length; index += 3) {
  27907. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27908. }
  27909. return true;
  27910. };
  27911. Geometry.prototype.isDisposed = function () {
  27912. return this._isDisposed;
  27913. };
  27914. Geometry.prototype._disposeVertexArrayObjects = function () {
  27915. if (this._vertexArrayObjects) {
  27916. for (var kind in this._vertexArrayObjects) {
  27917. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27918. }
  27919. this._vertexArrayObjects = {};
  27920. }
  27921. };
  27922. Geometry.prototype.dispose = function () {
  27923. var meshes = this._meshes;
  27924. var numOfMeshes = meshes.length;
  27925. var index;
  27926. for (index = 0; index < numOfMeshes; index++) {
  27927. this.releaseForMesh(meshes[index]);
  27928. }
  27929. this._meshes = [];
  27930. this._disposeVertexArrayObjects();
  27931. for (var kind in this._vertexBuffers) {
  27932. this._vertexBuffers[kind].dispose();
  27933. }
  27934. this._vertexBuffers = {};
  27935. this._totalVertices = 0;
  27936. if (this._indexBuffer) {
  27937. this._engine._releaseBuffer(this._indexBuffer);
  27938. }
  27939. this._indexBuffer = null;
  27940. this._indices = [];
  27941. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27942. this.delayLoadingFile = null;
  27943. this._delayLoadingFunction = null;
  27944. this._delayInfo = [];
  27945. this._boundingInfo = null;
  27946. this._scene.removeGeometry(this);
  27947. this._isDisposed = true;
  27948. };
  27949. Geometry.prototype.copy = function (id) {
  27950. var vertexData = new BABYLON.VertexData();
  27951. vertexData.indices = [];
  27952. var indices = this.getIndices();
  27953. for (var index = 0; index < indices.length; index++) {
  27954. vertexData.indices.push(indices[index]);
  27955. }
  27956. var updatable = false;
  27957. var stopChecking = false;
  27958. var kind;
  27959. for (kind in this._vertexBuffers) {
  27960. // using slice() to make a copy of the array and not just reference it
  27961. var data = this.getVerticesData(kind);
  27962. if (data instanceof Float32Array) {
  27963. vertexData.set(new Float32Array(data), kind);
  27964. }
  27965. else {
  27966. vertexData.set(data.slice(0), kind);
  27967. }
  27968. if (!stopChecking) {
  27969. updatable = this.getVertexBuffer(kind).isUpdatable();
  27970. stopChecking = !updatable;
  27971. }
  27972. }
  27973. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27974. geometry.delayLoadState = this.delayLoadState;
  27975. geometry.delayLoadingFile = this.delayLoadingFile;
  27976. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27977. for (kind in this._delayInfo) {
  27978. geometry._delayInfo = geometry._delayInfo || [];
  27979. geometry._delayInfo.push(kind);
  27980. }
  27981. // Bounding info
  27982. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27983. return geometry;
  27984. };
  27985. Geometry.prototype.serialize = function () {
  27986. var serializationObject = {};
  27987. serializationObject.id = this.id;
  27988. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27989. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27990. }
  27991. return serializationObject;
  27992. };
  27993. Geometry.prototype.toNumberArray = function (origin) {
  27994. if (Array.isArray(origin)) {
  27995. return origin;
  27996. }
  27997. else {
  27998. return Array.prototype.slice.call(origin);
  27999. }
  28000. };
  28001. Geometry.prototype.serializeVerticeData = function () {
  28002. var serializationObject = this.serialize();
  28003. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28004. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  28005. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  28006. serializationObject.positions._updatable = true;
  28007. }
  28008. }
  28009. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28010. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  28011. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  28012. serializationObject.normals._updatable = true;
  28013. }
  28014. }
  28015. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28016. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  28017. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  28018. serializationObject.uvs._updatable = true;
  28019. }
  28020. }
  28021. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28022. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  28023. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  28024. serializationObject.uv2s._updatable = true;
  28025. }
  28026. }
  28027. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28028. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  28029. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  28030. serializationObject.uv3s._updatable = true;
  28031. }
  28032. }
  28033. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28034. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  28035. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  28036. serializationObject.uv4s._updatable = true;
  28037. }
  28038. }
  28039. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28040. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  28041. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  28042. serializationObject.uv5s._updatable = true;
  28043. }
  28044. }
  28045. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28046. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  28047. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  28048. serializationObject.uv6s._updatable = true;
  28049. }
  28050. }
  28051. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28052. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  28053. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  28054. serializationObject.colors._updatable = true;
  28055. }
  28056. }
  28057. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28058. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  28059. serializationObject.matricesIndices._isExpanded = true;
  28060. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  28061. serializationObject.matricesIndices._updatable = true;
  28062. }
  28063. }
  28064. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28065. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  28066. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  28067. serializationObject.matricesWeights._updatable = true;
  28068. }
  28069. }
  28070. serializationObject.indices = this.toNumberArray(this.getIndices());
  28071. return serializationObject;
  28072. };
  28073. // Statics
  28074. Geometry.ExtractFromMesh = function (mesh, id) {
  28075. var geometry = mesh._geometry;
  28076. if (!geometry) {
  28077. return null;
  28078. }
  28079. return geometry.copy(id);
  28080. };
  28081. /**
  28082. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  28083. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28084. * Be aware Math.random() could cause collisions, but:
  28085. * "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"
  28086. */
  28087. Geometry.RandomId = function () {
  28088. return BABYLON.Tools.RandomId();
  28089. };
  28090. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28091. var scene = mesh.getScene();
  28092. // Geometry
  28093. var geometryId = parsedGeometry.geometryId;
  28094. if (geometryId) {
  28095. var geometry = scene.getGeometryByID(geometryId);
  28096. if (geometry) {
  28097. geometry.applyToMesh(mesh);
  28098. }
  28099. }
  28100. else if (parsedGeometry instanceof ArrayBuffer) {
  28101. var binaryInfo = mesh._binaryInfo;
  28102. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28103. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28104. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28105. }
  28106. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28107. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28108. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28109. }
  28110. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28111. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28112. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28113. }
  28114. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28115. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28116. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28117. }
  28118. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28119. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28120. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28121. }
  28122. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28123. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28124. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28125. }
  28126. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28127. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28128. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28129. }
  28130. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28131. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28132. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28133. }
  28134. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28135. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28136. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28137. }
  28138. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28139. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28140. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28141. }
  28142. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28143. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28144. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28145. }
  28146. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28147. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28148. mesh.setIndices(indicesData);
  28149. }
  28150. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28151. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28152. mesh.subMeshes = [];
  28153. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28154. var materialIndex = subMeshesData[(i * 5) + 0];
  28155. var verticesStart = subMeshesData[(i * 5) + 1];
  28156. var verticesCount = subMeshesData[(i * 5) + 2];
  28157. var indexStart = subMeshesData[(i * 5) + 3];
  28158. var indexCount = subMeshesData[(i * 5) + 4];
  28159. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28160. }
  28161. }
  28162. }
  28163. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28164. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  28165. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  28166. if (parsedGeometry.uvs) {
  28167. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  28168. }
  28169. if (parsedGeometry.uvs2) {
  28170. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  28171. }
  28172. if (parsedGeometry.uvs3) {
  28173. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  28174. }
  28175. if (parsedGeometry.uvs4) {
  28176. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  28177. }
  28178. if (parsedGeometry.uvs5) {
  28179. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  28180. }
  28181. if (parsedGeometry.uvs6) {
  28182. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  28183. }
  28184. if (parsedGeometry.colors) {
  28185. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  28186. }
  28187. if (parsedGeometry.matricesIndices) {
  28188. if (!parsedGeometry.matricesIndices._isExpanded) {
  28189. var floatIndices = [];
  28190. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28191. var matricesIndex = parsedGeometry.matricesIndices[i];
  28192. floatIndices.push(matricesIndex & 0x000000FF);
  28193. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28194. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28195. floatIndices.push(matricesIndex >> 24);
  28196. }
  28197. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  28198. }
  28199. else {
  28200. delete parsedGeometry.matricesIndices._isExpanded;
  28201. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  28202. }
  28203. }
  28204. if (parsedGeometry.matricesIndicesExtra) {
  28205. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28206. var floatIndices = [];
  28207. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28208. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28209. floatIndices.push(matricesIndex & 0x000000FF);
  28210. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28211. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28212. floatIndices.push(matricesIndex >> 24);
  28213. }
  28214. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  28215. }
  28216. else {
  28217. delete parsedGeometry.matricesIndices._isExpanded;
  28218. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  28219. }
  28220. }
  28221. if (parsedGeometry.matricesWeights) {
  28222. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  28223. }
  28224. if (parsedGeometry.matricesWeightsExtra) {
  28225. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  28226. }
  28227. mesh.setIndices(parsedGeometry.indices);
  28228. }
  28229. // SubMeshes
  28230. if (parsedGeometry.subMeshes) {
  28231. mesh.subMeshes = [];
  28232. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28233. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28234. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28235. }
  28236. }
  28237. // Flat shading
  28238. if (mesh._shouldGenerateFlatShading) {
  28239. mesh.convertToFlatShadedMesh();
  28240. delete mesh._shouldGenerateFlatShading;
  28241. }
  28242. // Update
  28243. mesh.computeWorldMatrix(true);
  28244. // Octree
  28245. if (scene['_selectionOctree']) {
  28246. scene['_selectionOctree'].addMesh(mesh);
  28247. }
  28248. };
  28249. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28250. if (scene.getGeometryByID(parsedVertexData.id)) {
  28251. return null; // null since geometry could be something else than a box...
  28252. }
  28253. var geometry = new Geometry(parsedVertexData.id, scene);
  28254. if (BABYLON.Tags) {
  28255. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28256. }
  28257. if (parsedVertexData.delayLoadingFile) {
  28258. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28259. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28260. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28261. geometry._delayInfo = [];
  28262. if (parsedVertexData.hasUVs) {
  28263. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28264. }
  28265. if (parsedVertexData.hasUVs2) {
  28266. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28267. }
  28268. if (parsedVertexData.hasUVs3) {
  28269. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28270. }
  28271. if (parsedVertexData.hasUVs4) {
  28272. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28273. }
  28274. if (parsedVertexData.hasUVs5) {
  28275. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28276. }
  28277. if (parsedVertexData.hasUVs6) {
  28278. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28279. }
  28280. if (parsedVertexData.hasColors) {
  28281. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28282. }
  28283. if (parsedVertexData.hasMatricesIndices) {
  28284. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28285. }
  28286. if (parsedVertexData.hasMatricesWeights) {
  28287. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28288. }
  28289. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28290. }
  28291. else {
  28292. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28293. }
  28294. scene.pushGeometry(geometry, true);
  28295. return geometry;
  28296. };
  28297. return Geometry;
  28298. }());
  28299. BABYLON.Geometry = Geometry;
  28300. /////// Primitives //////////////////////////////////////////////
  28301. (function (Geometry) {
  28302. var Primitives;
  28303. (function (Primitives) {
  28304. /// Abstract class
  28305. var _Primitive = (function (_super) {
  28306. __extends(_Primitive, _super);
  28307. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28308. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  28309. _this._canBeRegenerated = _canBeRegenerated;
  28310. _this._beingRegenerated = true;
  28311. _this.regenerate();
  28312. _this._beingRegenerated = false;
  28313. return _this;
  28314. }
  28315. _Primitive.prototype.canBeRegenerated = function () {
  28316. return this._canBeRegenerated;
  28317. };
  28318. _Primitive.prototype.regenerate = function () {
  28319. if (!this._canBeRegenerated) {
  28320. return;
  28321. }
  28322. this._beingRegenerated = true;
  28323. this.setAllVerticesData(this._regenerateVertexData(), false);
  28324. this._beingRegenerated = false;
  28325. };
  28326. _Primitive.prototype.asNewGeometry = function (id) {
  28327. return _super.prototype.copy.call(this, id);
  28328. };
  28329. // overrides
  28330. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28331. if (!this._beingRegenerated) {
  28332. return;
  28333. }
  28334. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28335. };
  28336. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28337. if (!this._beingRegenerated) {
  28338. return;
  28339. }
  28340. _super.prototype.setVerticesData.call(this, kind, data, false);
  28341. };
  28342. // to override
  28343. // protected
  28344. _Primitive.prototype._regenerateVertexData = function () {
  28345. throw new Error("Abstract method");
  28346. };
  28347. _Primitive.prototype.copy = function (id) {
  28348. throw new Error("Must be overriden in sub-classes.");
  28349. };
  28350. _Primitive.prototype.serialize = function () {
  28351. var serializationObject = _super.prototype.serialize.call(this);
  28352. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28353. return serializationObject;
  28354. };
  28355. return _Primitive;
  28356. }(Geometry));
  28357. Primitives._Primitive = _Primitive;
  28358. var Ribbon = (function (_super) {
  28359. __extends(Ribbon, _super);
  28360. // Members
  28361. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28362. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28363. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28364. _this.pathArray = pathArray;
  28365. _this.closeArray = closeArray;
  28366. _this.closePath = closePath;
  28367. _this.offset = offset;
  28368. _this.side = side;
  28369. return _this;
  28370. }
  28371. Ribbon.prototype._regenerateVertexData = function () {
  28372. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28373. };
  28374. Ribbon.prototype.copy = function (id) {
  28375. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28376. };
  28377. return Ribbon;
  28378. }(_Primitive));
  28379. Primitives.Ribbon = Ribbon;
  28380. var Box = (function (_super) {
  28381. __extends(Box, _super);
  28382. // Members
  28383. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28384. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28385. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28386. _this.size = size;
  28387. _this.side = side;
  28388. return _this;
  28389. }
  28390. Box.prototype._regenerateVertexData = function () {
  28391. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28392. };
  28393. Box.prototype.copy = function (id) {
  28394. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28395. };
  28396. Box.prototype.serialize = function () {
  28397. var serializationObject = _super.prototype.serialize.call(this);
  28398. serializationObject.size = this.size;
  28399. return serializationObject;
  28400. };
  28401. Box.Parse = function (parsedBox, scene) {
  28402. if (scene.getGeometryByID(parsedBox.id)) {
  28403. return null; // null since geometry could be something else than a box...
  28404. }
  28405. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28406. if (BABYLON.Tags) {
  28407. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28408. }
  28409. scene.pushGeometry(box, true);
  28410. return box;
  28411. };
  28412. return Box;
  28413. }(_Primitive));
  28414. Primitives.Box = Box;
  28415. var Sphere = (function (_super) {
  28416. __extends(Sphere, _super);
  28417. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28418. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28419. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28420. _this.segments = segments;
  28421. _this.diameter = diameter;
  28422. _this.side = side;
  28423. return _this;
  28424. }
  28425. Sphere.prototype._regenerateVertexData = function () {
  28426. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28427. };
  28428. Sphere.prototype.copy = function (id) {
  28429. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28430. };
  28431. Sphere.prototype.serialize = function () {
  28432. var serializationObject = _super.prototype.serialize.call(this);
  28433. serializationObject.segments = this.segments;
  28434. serializationObject.diameter = this.diameter;
  28435. return serializationObject;
  28436. };
  28437. Sphere.Parse = function (parsedSphere, scene) {
  28438. if (scene.getGeometryByID(parsedSphere.id)) {
  28439. return null; // null since geometry could be something else than a sphere...
  28440. }
  28441. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28442. if (BABYLON.Tags) {
  28443. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28444. }
  28445. scene.pushGeometry(sphere, true);
  28446. return sphere;
  28447. };
  28448. return Sphere;
  28449. }(_Primitive));
  28450. Primitives.Sphere = Sphere;
  28451. var Disc = (function (_super) {
  28452. __extends(Disc, _super);
  28453. // Members
  28454. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28455. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28456. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28457. _this.radius = radius;
  28458. _this.tessellation = tessellation;
  28459. _this.side = side;
  28460. return _this;
  28461. }
  28462. Disc.prototype._regenerateVertexData = function () {
  28463. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28464. };
  28465. Disc.prototype.copy = function (id) {
  28466. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28467. };
  28468. return Disc;
  28469. }(_Primitive));
  28470. Primitives.Disc = Disc;
  28471. var Cylinder = (function (_super) {
  28472. __extends(Cylinder, _super);
  28473. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28474. if (subdivisions === void 0) { subdivisions = 1; }
  28475. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28476. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28477. _this.height = height;
  28478. _this.diameterTop = diameterTop;
  28479. _this.diameterBottom = diameterBottom;
  28480. _this.tessellation = tessellation;
  28481. _this.subdivisions = subdivisions;
  28482. _this.side = side;
  28483. return _this;
  28484. }
  28485. Cylinder.prototype._regenerateVertexData = function () {
  28486. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28487. };
  28488. Cylinder.prototype.copy = function (id) {
  28489. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28490. };
  28491. Cylinder.prototype.serialize = function () {
  28492. var serializationObject = _super.prototype.serialize.call(this);
  28493. serializationObject.height = this.height;
  28494. serializationObject.diameterTop = this.diameterTop;
  28495. serializationObject.diameterBottom = this.diameterBottom;
  28496. serializationObject.tessellation = this.tessellation;
  28497. return serializationObject;
  28498. };
  28499. Cylinder.Parse = function (parsedCylinder, scene) {
  28500. if (scene.getGeometryByID(parsedCylinder.id)) {
  28501. return null; // null since geometry could be something else than a cylinder...
  28502. }
  28503. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28504. if (BABYLON.Tags) {
  28505. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28506. }
  28507. scene.pushGeometry(cylinder, true);
  28508. return cylinder;
  28509. };
  28510. return Cylinder;
  28511. }(_Primitive));
  28512. Primitives.Cylinder = Cylinder;
  28513. var Torus = (function (_super) {
  28514. __extends(Torus, _super);
  28515. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28516. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28517. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28518. _this.diameter = diameter;
  28519. _this.thickness = thickness;
  28520. _this.tessellation = tessellation;
  28521. _this.side = side;
  28522. return _this;
  28523. }
  28524. Torus.prototype._regenerateVertexData = function () {
  28525. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28526. };
  28527. Torus.prototype.copy = function (id) {
  28528. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28529. };
  28530. Torus.prototype.serialize = function () {
  28531. var serializationObject = _super.prototype.serialize.call(this);
  28532. serializationObject.diameter = this.diameter;
  28533. serializationObject.thickness = this.thickness;
  28534. serializationObject.tessellation = this.tessellation;
  28535. return serializationObject;
  28536. };
  28537. Torus.Parse = function (parsedTorus, scene) {
  28538. if (scene.getGeometryByID(parsedTorus.id)) {
  28539. return null; // null since geometry could be something else than a torus...
  28540. }
  28541. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28542. if (BABYLON.Tags) {
  28543. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28544. }
  28545. scene.pushGeometry(torus, true);
  28546. return torus;
  28547. };
  28548. return Torus;
  28549. }(_Primitive));
  28550. Primitives.Torus = Torus;
  28551. var Ground = (function (_super) {
  28552. __extends(Ground, _super);
  28553. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28554. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28555. _this.width = width;
  28556. _this.height = height;
  28557. _this.subdivisions = subdivisions;
  28558. return _this;
  28559. }
  28560. Ground.prototype._regenerateVertexData = function () {
  28561. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28562. };
  28563. Ground.prototype.copy = function (id) {
  28564. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28565. };
  28566. Ground.prototype.serialize = function () {
  28567. var serializationObject = _super.prototype.serialize.call(this);
  28568. serializationObject.width = this.width;
  28569. serializationObject.height = this.height;
  28570. serializationObject.subdivisions = this.subdivisions;
  28571. return serializationObject;
  28572. };
  28573. Ground.Parse = function (parsedGround, scene) {
  28574. if (scene.getGeometryByID(parsedGround.id)) {
  28575. return null; // null since geometry could be something else than a ground...
  28576. }
  28577. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28578. if (BABYLON.Tags) {
  28579. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28580. }
  28581. scene.pushGeometry(ground, true);
  28582. return ground;
  28583. };
  28584. return Ground;
  28585. }(_Primitive));
  28586. Primitives.Ground = Ground;
  28587. var TiledGround = (function (_super) {
  28588. __extends(TiledGround, _super);
  28589. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28590. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28591. _this.xmin = xmin;
  28592. _this.zmin = zmin;
  28593. _this.xmax = xmax;
  28594. _this.zmax = zmax;
  28595. _this.subdivisions = subdivisions;
  28596. _this.precision = precision;
  28597. return _this;
  28598. }
  28599. TiledGround.prototype._regenerateVertexData = function () {
  28600. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28601. };
  28602. TiledGround.prototype.copy = function (id) {
  28603. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28604. };
  28605. return TiledGround;
  28606. }(_Primitive));
  28607. Primitives.TiledGround = TiledGround;
  28608. var Plane = (function (_super) {
  28609. __extends(Plane, _super);
  28610. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28611. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28612. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28613. _this.size = size;
  28614. _this.side = side;
  28615. return _this;
  28616. }
  28617. Plane.prototype._regenerateVertexData = function () {
  28618. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28619. };
  28620. Plane.prototype.copy = function (id) {
  28621. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28622. };
  28623. Plane.prototype.serialize = function () {
  28624. var serializationObject = _super.prototype.serialize.call(this);
  28625. serializationObject.size = this.size;
  28626. return serializationObject;
  28627. };
  28628. Plane.Parse = function (parsedPlane, scene) {
  28629. if (scene.getGeometryByID(parsedPlane.id)) {
  28630. return null; // null since geometry could be something else than a ground...
  28631. }
  28632. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28633. if (BABYLON.Tags) {
  28634. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28635. }
  28636. scene.pushGeometry(plane, true);
  28637. return plane;
  28638. };
  28639. return Plane;
  28640. }(_Primitive));
  28641. Primitives.Plane = Plane;
  28642. var TorusKnot = (function (_super) {
  28643. __extends(TorusKnot, _super);
  28644. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28645. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28646. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28647. _this.radius = radius;
  28648. _this.tube = tube;
  28649. _this.radialSegments = radialSegments;
  28650. _this.tubularSegments = tubularSegments;
  28651. _this.p = p;
  28652. _this.q = q;
  28653. _this.side = side;
  28654. return _this;
  28655. }
  28656. TorusKnot.prototype._regenerateVertexData = function () {
  28657. 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 });
  28658. };
  28659. TorusKnot.prototype.copy = function (id) {
  28660. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28661. };
  28662. TorusKnot.prototype.serialize = function () {
  28663. var serializationObject = _super.prototype.serialize.call(this);
  28664. serializationObject.radius = this.radius;
  28665. serializationObject.tube = this.tube;
  28666. serializationObject.radialSegments = this.radialSegments;
  28667. serializationObject.tubularSegments = this.tubularSegments;
  28668. serializationObject.p = this.p;
  28669. serializationObject.q = this.q;
  28670. return serializationObject;
  28671. };
  28672. ;
  28673. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28674. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28675. return null; // null since geometry could be something else than a ground...
  28676. }
  28677. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28678. if (BABYLON.Tags) {
  28679. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28680. }
  28681. scene.pushGeometry(torusKnot, true);
  28682. return torusKnot;
  28683. };
  28684. return TorusKnot;
  28685. }(_Primitive));
  28686. Primitives.TorusKnot = TorusKnot;
  28687. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28688. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28689. })(BABYLON || (BABYLON = {}));
  28690. //# sourceMappingURL=babylon.geometry.js.map
  28691. var BABYLON;
  28692. (function (BABYLON) {
  28693. var PostProcessManager = (function () {
  28694. function PostProcessManager(scene) {
  28695. this._vertexBuffers = {};
  28696. this._scene = scene;
  28697. }
  28698. PostProcessManager.prototype._prepareBuffers = function () {
  28699. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28700. return;
  28701. }
  28702. // VBO
  28703. var vertices = [];
  28704. vertices.push(1, 1);
  28705. vertices.push(-1, 1);
  28706. vertices.push(-1, -1);
  28707. vertices.push(1, -1);
  28708. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28709. // Indices
  28710. var indices = [];
  28711. indices.push(0);
  28712. indices.push(1);
  28713. indices.push(2);
  28714. indices.push(0);
  28715. indices.push(2);
  28716. indices.push(3);
  28717. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28718. };
  28719. // Methods
  28720. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28721. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28722. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28723. return false;
  28724. }
  28725. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28726. return true;
  28727. };
  28728. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28729. var engine = this._scene.getEngine();
  28730. for (var index = 0; index < postProcesses.length; index++) {
  28731. if (index < postProcesses.length - 1) {
  28732. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28733. }
  28734. else {
  28735. if (targetTexture) {
  28736. engine.bindFramebuffer(targetTexture);
  28737. }
  28738. else {
  28739. engine.restoreDefaultFramebuffer();
  28740. }
  28741. }
  28742. var pp = postProcesses[index];
  28743. var effect = pp.apply();
  28744. if (effect) {
  28745. pp.onBeforeRenderObservable.notifyObservers(effect);
  28746. // VBOs
  28747. this._prepareBuffers();
  28748. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28749. // Draw order
  28750. engine.draw(true, 0, 6);
  28751. pp.onAfterRenderObservable.notifyObservers(effect);
  28752. }
  28753. }
  28754. // Restore depth buffer
  28755. engine.setDepthBuffer(true);
  28756. engine.setDepthWrite(true);
  28757. };
  28758. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28759. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28760. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28761. return;
  28762. }
  28763. var engine = this._scene.getEngine();
  28764. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28765. if (index < len - 1) {
  28766. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28767. }
  28768. else {
  28769. if (targetTexture) {
  28770. engine.bindFramebuffer(targetTexture, faceIndex);
  28771. }
  28772. else {
  28773. engine.restoreDefaultFramebuffer();
  28774. }
  28775. }
  28776. if (doNotPresent) {
  28777. break;
  28778. }
  28779. var pp = postProcesses[index];
  28780. var effect = pp.apply();
  28781. if (effect) {
  28782. pp.onBeforeRenderObservable.notifyObservers(effect);
  28783. // VBOs
  28784. this._prepareBuffers();
  28785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28786. // Draw order
  28787. engine.draw(true, 0, 6);
  28788. pp.onAfterRenderObservable.notifyObservers(effect);
  28789. }
  28790. }
  28791. // Restore states
  28792. engine.setDepthBuffer(true);
  28793. engine.setDepthWrite(true);
  28794. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28795. };
  28796. PostProcessManager.prototype.dispose = function () {
  28797. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28798. if (buffer) {
  28799. buffer.dispose();
  28800. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28801. }
  28802. if (this._indexBuffer) {
  28803. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28804. this._indexBuffer = null;
  28805. }
  28806. };
  28807. return PostProcessManager;
  28808. }());
  28809. BABYLON.PostProcessManager = PostProcessManager;
  28810. })(BABYLON || (BABYLON = {}));
  28811. //# sourceMappingURL=babylon.postProcessManager.js.map
  28812. var BABYLON;
  28813. (function (BABYLON) {
  28814. /**
  28815. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  28816. */
  28817. var PerformanceMonitor = (function () {
  28818. /**
  28819. * constructor
  28820. * @param frameSampleSize The number of samples required to saturate the sliding window
  28821. */
  28822. function PerformanceMonitor(frameSampleSize) {
  28823. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  28824. this._enabled = true;
  28825. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  28826. }
  28827. /**
  28828. * Samples current frame
  28829. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  28830. */
  28831. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  28832. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  28833. if (!this._enabled)
  28834. return;
  28835. if (this._lastFrameTimeMs != null) {
  28836. var dt = timeMs - this._lastFrameTimeMs;
  28837. this._rollingFrameTime.add(dt);
  28838. }
  28839. this._lastFrameTimeMs = timeMs;
  28840. };
  28841. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  28842. /**
  28843. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  28844. * @return Average frame time in milliseconds
  28845. */
  28846. get: function () {
  28847. return this._rollingFrameTime.average;
  28848. },
  28849. enumerable: true,
  28850. configurable: true
  28851. });
  28852. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  28853. /**
  28854. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  28855. * @return Frame time variance in milliseconds squared
  28856. */
  28857. get: function () {
  28858. return this._rollingFrameTime.variance;
  28859. },
  28860. enumerable: true,
  28861. configurable: true
  28862. });
  28863. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  28864. /**
  28865. * Returns the frame time of the most recent frame
  28866. * @return Frame time in milliseconds
  28867. */
  28868. get: function () {
  28869. return this._rollingFrameTime.history(0);
  28870. },
  28871. enumerable: true,
  28872. configurable: true
  28873. });
  28874. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  28875. /**
  28876. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  28877. * @return Framerate in frames per second
  28878. */
  28879. get: function () {
  28880. return 1000.0 / this._rollingFrameTime.average;
  28881. },
  28882. enumerable: true,
  28883. configurable: true
  28884. });
  28885. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  28886. /**
  28887. * Returns the average framerate in frames per second using the most recent frame time
  28888. * @return Framerate in frames per second
  28889. */
  28890. get: function () {
  28891. return 1000.0 / this._rollingFrameTime.history(0);
  28892. },
  28893. enumerable: true,
  28894. configurable: true
  28895. });
  28896. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  28897. /**
  28898. * Returns true if enough samples have been taken to completely fill the sliding window
  28899. * @return true if saturated
  28900. */
  28901. get: function () {
  28902. return this._rollingFrameTime.isSaturated();
  28903. },
  28904. enumerable: true,
  28905. configurable: true
  28906. });
  28907. /**
  28908. * Enables contributions to the sliding window sample set
  28909. */
  28910. PerformanceMonitor.prototype.enable = function () {
  28911. this._enabled = true;
  28912. };
  28913. /**
  28914. * Disables contributions to the sliding window sample set
  28915. * Samples will not be interpolated over the disabled period
  28916. */
  28917. PerformanceMonitor.prototype.disable = function () {
  28918. this._enabled = false;
  28919. //clear last sample to avoid interpolating over the disabled period when next enabled
  28920. this._lastFrameTimeMs = null;
  28921. this._lastChangeTimeMs = null;
  28922. };
  28923. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  28924. /**
  28925. * Returns true if sampling is enabled
  28926. * @return true if enabled
  28927. */
  28928. get: function () {
  28929. return this._enabled;
  28930. },
  28931. enumerable: true,
  28932. configurable: true
  28933. });
  28934. /**
  28935. * Resets performance monitor
  28936. */
  28937. PerformanceMonitor.prototype.reset = function () {
  28938. //clear last sample to avoid interpolating over the disabled period when next enabled
  28939. this._lastFrameTimeMs = null;
  28940. this._lastChangeTimeMs = null;
  28941. //wipe record
  28942. this._rollingFrameTime.reset();
  28943. };
  28944. return PerformanceMonitor;
  28945. }());
  28946. BABYLON.PerformanceMonitor = PerformanceMonitor;
  28947. /**
  28948. * RollingAverage
  28949. *
  28950. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  28951. */
  28952. var RollingAverage = (function () {
  28953. /**
  28954. * constructor
  28955. * @param length The number of samples required to saturate the sliding window
  28956. */
  28957. function RollingAverage(length) {
  28958. this._samples = new Array(length);
  28959. this.reset();
  28960. }
  28961. /**
  28962. * Adds a sample to the sample set
  28963. * @param v The sample value
  28964. */
  28965. RollingAverage.prototype.add = function (v) {
  28966. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  28967. var delta;
  28968. //we need to check if we've already wrapped round
  28969. if (this.isSaturated()) {
  28970. //remove bottom of stack from mean
  28971. var bottomValue = this._samples[this._pos];
  28972. delta = bottomValue - this.average;
  28973. this.average -= delta / (this._sampleCount - 1);
  28974. this._m2 -= delta * (bottomValue - this.average);
  28975. }
  28976. else {
  28977. this._sampleCount++;
  28978. }
  28979. //add new value to mean
  28980. delta = v - this.average;
  28981. this.average += delta / (this._sampleCount);
  28982. this._m2 += delta * (v - this.average);
  28983. //set the new variance
  28984. this.variance = this._m2 / (this._sampleCount - 1);
  28985. this._samples[this._pos] = v;
  28986. this._pos++;
  28987. this._pos %= this._samples.length; //positive wrap around
  28988. };
  28989. /**
  28990. * Returns previously added values or null if outside of history or outside the sliding window domain
  28991. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  28992. * @return Value previously recorded with add() or null if outside of range
  28993. */
  28994. RollingAverage.prototype.history = function (i) {
  28995. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  28996. return null;
  28997. }
  28998. var i0 = this._wrapPosition(this._pos - 1.0);
  28999. return this._samples[this._wrapPosition(i0 - i)];
  29000. };
  29001. /**
  29002. * Returns true if enough samples have been taken to completely fill the sliding window
  29003. * @return true if sample-set saturated
  29004. */
  29005. RollingAverage.prototype.isSaturated = function () {
  29006. return this._sampleCount >= this._samples.length;
  29007. };
  29008. /**
  29009. * Resets the rolling average (equivalent to 0 samples taken so far)
  29010. */
  29011. RollingAverage.prototype.reset = function () {
  29012. this.average = 0;
  29013. this.variance = 0;
  29014. this._sampleCount = 0;
  29015. this._pos = 0;
  29016. this._m2 = 0;
  29017. };
  29018. /**
  29019. * Wraps a value around the sample range boundaries
  29020. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  29021. * @return Wrapped position in sample range
  29022. */
  29023. RollingAverage.prototype._wrapPosition = function (i) {
  29024. var max = this._samples.length;
  29025. return ((i % max) + max) % max;
  29026. };
  29027. return RollingAverage;
  29028. }());
  29029. BABYLON.RollingAverage = RollingAverage;
  29030. })(BABYLON || (BABYLON = {}));
  29031. //# sourceMappingURL=babylon.performanceMonitor.js.map
  29032. var BABYLON;
  29033. (function (BABYLON) {
  29034. var StandardMaterialDefines = (function (_super) {
  29035. __extends(StandardMaterialDefines, _super);
  29036. function StandardMaterialDefines() {
  29037. var _this = _super.call(this) || this;
  29038. _this.MAINUV1 = false;
  29039. _this.MAINUV2 = false;
  29040. _this.DIFFUSE = false;
  29041. _this.DIFFUSEDIRECTUV = 0;
  29042. _this.AMBIENT = false;
  29043. _this.AMBIENTDIRECTUV = 0;
  29044. _this.OPACITY = false;
  29045. _this.OPACITYDIRECTUV = 0;
  29046. _this.OPACITYRGB = false;
  29047. _this.REFLECTION = false;
  29048. _this.EMISSIVE = false;
  29049. _this.EMISSIVEDIRECTUV = 0;
  29050. _this.SPECULAR = false;
  29051. _this.SPECULARDIRECTUV = 0;
  29052. _this.BUMP = false;
  29053. _this.BUMPDIRECTUV = 0;
  29054. _this.PARALLAX = false;
  29055. _this.PARALLAXOCCLUSION = false;
  29056. _this.SPECULAROVERALPHA = false;
  29057. _this.CLIPPLANE = false;
  29058. _this.ALPHATEST = false;
  29059. _this.ALPHAFROMDIFFUSE = false;
  29060. _this.POINTSIZE = false;
  29061. _this.FOG = false;
  29062. _this.SPECULARTERM = false;
  29063. _this.DIFFUSEFRESNEL = false;
  29064. _this.OPACITYFRESNEL = false;
  29065. _this.REFLECTIONFRESNEL = false;
  29066. _this.REFRACTIONFRESNEL = false;
  29067. _this.EMISSIVEFRESNEL = false;
  29068. _this.FRESNEL = false;
  29069. _this.NORMAL = false;
  29070. _this.UV1 = false;
  29071. _this.UV2 = false;
  29072. _this.VERTEXCOLOR = false;
  29073. _this.VERTEXALPHA = false;
  29074. _this.NUM_BONE_INFLUENCERS = 0;
  29075. _this.BonesPerMesh = 0;
  29076. _this.INSTANCES = false;
  29077. _this.GLOSSINESS = false;
  29078. _this.ROUGHNESS = false;
  29079. _this.EMISSIVEASILLUMINATION = false;
  29080. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29081. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29082. _this.LIGHTMAP = false;
  29083. _this.LIGHTMAPDIRECTUV = 0;
  29084. _this.USELIGHTMAPASSHADOWMAP = false;
  29085. _this.REFLECTIONMAP_3D = false;
  29086. _this.REFLECTIONMAP_SPHERICAL = false;
  29087. _this.REFLECTIONMAP_PLANAR = false;
  29088. _this.REFLECTIONMAP_CUBIC = false;
  29089. _this.REFLECTIONMAP_PROJECTION = false;
  29090. _this.REFLECTIONMAP_SKYBOX = false;
  29091. _this.REFLECTIONMAP_EXPLICIT = false;
  29092. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29093. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29094. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29095. _this.INVERTCUBICMAP = false;
  29096. _this.LOGARITHMICDEPTH = false;
  29097. _this.REFRACTION = false;
  29098. _this.REFRACTIONMAP_3D = false;
  29099. _this.REFLECTIONOVERALPHA = false;
  29100. _this.INVERTNORMALMAPX = false;
  29101. _this.INVERTNORMALMAPY = false;
  29102. _this.TWOSIDEDLIGHTING = false;
  29103. _this.SHADOWFLOAT = false;
  29104. _this.MORPHTARGETS = false;
  29105. _this.MORPHTARGETS_NORMAL = false;
  29106. _this.MORPHTARGETS_TANGENT = false;
  29107. _this.NUM_MORPH_INFLUENCERS = 0;
  29108. _this.USERIGHTHANDEDSYSTEM = false;
  29109. _this.IMAGEPROCESSING = false;
  29110. _this.VIGNETTE = false;
  29111. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  29112. _this.VIGNETTEBLENDMODEOPAQUE = false;
  29113. _this.TONEMAPPING = false;
  29114. _this.CONTRAST = false;
  29115. _this.COLORCURVES = false;
  29116. _this.COLORGRADING = false;
  29117. _this.SAMPLER3DGREENDEPTH = false;
  29118. _this.SAMPLER3DBGRMAP = false;
  29119. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  29120. _this.EXPOSURE = false;
  29121. _this.rebuild();
  29122. return _this;
  29123. }
  29124. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  29125. var modes = [
  29126. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  29127. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  29128. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  29129. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  29130. ];
  29131. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  29132. var mode = modes_1[_i];
  29133. this[mode] = (mode === modeToEnable);
  29134. }
  29135. };
  29136. return StandardMaterialDefines;
  29137. }(BABYLON.MaterialDefines));
  29138. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  29139. var StandardMaterial = (function (_super) {
  29140. __extends(StandardMaterial, _super);
  29141. function StandardMaterial(name, scene) {
  29142. var _this = _super.call(this, name, scene) || this;
  29143. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  29144. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  29145. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  29146. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  29147. _this.specularPower = 64;
  29148. _this._useAlphaFromDiffuseTexture = false;
  29149. _this._useEmissiveAsIllumination = false;
  29150. _this._linkEmissiveWithDiffuse = false;
  29151. _this._useSpecularOverAlpha = false;
  29152. _this._useReflectionOverAlpha = false;
  29153. _this._disableLighting = false;
  29154. _this._useParallax = false;
  29155. _this._useParallaxOcclusion = false;
  29156. _this.parallaxScaleBias = 0.05;
  29157. _this._roughness = 0;
  29158. _this.indexOfRefraction = 0.98;
  29159. _this.invertRefractionY = true;
  29160. _this._useLightmapAsShadowmap = false;
  29161. _this._useReflectionFresnelFromSpecular = false;
  29162. _this._useGlossinessFromSpecularMapAlpha = false;
  29163. _this._maxSimultaneousLights = 4;
  29164. /**
  29165. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29166. */
  29167. _this._invertNormalMapX = false;
  29168. /**
  29169. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29170. */
  29171. _this._invertNormalMapY = false;
  29172. /**
  29173. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  29174. */
  29175. _this._twoSidedLighting = false;
  29176. _this._renderTargets = new BABYLON.SmartArray(16);
  29177. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29178. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29179. // Setup the default processing configuration to the scene.
  29180. _this._attachImageProcessingConfiguration(null);
  29181. _this.getRenderTargetTextures = function () {
  29182. _this._renderTargets.reset();
  29183. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  29184. _this._renderTargets.push(_this._reflectionTexture);
  29185. }
  29186. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  29187. _this._renderTargets.push(_this._refractionTexture);
  29188. }
  29189. return _this._renderTargets;
  29190. };
  29191. return _this;
  29192. }
  29193. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  29194. /**
  29195. * Gets the image processing configuration used either in this material.
  29196. */
  29197. get: function () {
  29198. return this._imageProcessingConfiguration;
  29199. },
  29200. /**
  29201. * Sets the Default image processing configuration used either in the this material.
  29202. *
  29203. * If sets to null, the scene one is in use.
  29204. */
  29205. set: function (value) {
  29206. this._attachImageProcessingConfiguration(value);
  29207. // Ensure the effect will be rebuilt.
  29208. this._markAllSubMeshesAsTexturesDirty();
  29209. },
  29210. enumerable: true,
  29211. configurable: true
  29212. });
  29213. /**
  29214. * Attaches a new image processing configuration to the Standard Material.
  29215. * @param configuration
  29216. */
  29217. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  29218. var _this = this;
  29219. if (configuration === this._imageProcessingConfiguration) {
  29220. return;
  29221. }
  29222. // Detaches observer.
  29223. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  29224. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  29225. }
  29226. // Pick the scene configuration if needed.
  29227. if (!configuration) {
  29228. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  29229. }
  29230. else {
  29231. this._imageProcessingConfiguration = configuration;
  29232. }
  29233. // Attaches observer.
  29234. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  29235. _this._markAllSubMeshesAsImageProcessingDirty();
  29236. });
  29237. };
  29238. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  29239. /**
  29240. * Gets wether the color curves effect is enabled.
  29241. */
  29242. get: function () {
  29243. return this.imageProcessingConfiguration.colorCurvesEnabled;
  29244. },
  29245. /**
  29246. * Sets wether the color curves effect is enabled.
  29247. */
  29248. set: function (value) {
  29249. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  29250. },
  29251. enumerable: true,
  29252. configurable: true
  29253. });
  29254. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  29255. /**
  29256. * Gets wether the color grading effect is enabled.
  29257. */
  29258. get: function () {
  29259. return this.imageProcessingConfiguration.colorGradingEnabled;
  29260. },
  29261. /**
  29262. * Gets wether the color grading effect is enabled.
  29263. */
  29264. set: function (value) {
  29265. this.imageProcessingConfiguration.colorGradingEnabled = value;
  29266. },
  29267. enumerable: true,
  29268. configurable: true
  29269. });
  29270. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  29271. /**
  29272. * Gets wether tonemapping is enabled or not.
  29273. */
  29274. get: function () {
  29275. return this._imageProcessingConfiguration.toneMappingEnabled;
  29276. },
  29277. /**
  29278. * Sets wether tonemapping is enabled or not
  29279. */
  29280. set: function (value) {
  29281. this._imageProcessingConfiguration.toneMappingEnabled = value;
  29282. },
  29283. enumerable: true,
  29284. configurable: true
  29285. });
  29286. ;
  29287. ;
  29288. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  29289. /**
  29290. * The camera exposure used on this material.
  29291. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29292. * This corresponds to a photographic exposure.
  29293. */
  29294. get: function () {
  29295. return this._imageProcessingConfiguration.exposure;
  29296. },
  29297. /**
  29298. * The camera exposure used on this material.
  29299. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29300. * This corresponds to a photographic exposure.
  29301. */
  29302. set: function (value) {
  29303. this._imageProcessingConfiguration.exposure = value;
  29304. },
  29305. enumerable: true,
  29306. configurable: true
  29307. });
  29308. ;
  29309. ;
  29310. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  29311. /**
  29312. * Gets The camera contrast used on this material.
  29313. */
  29314. get: function () {
  29315. return this._imageProcessingConfiguration.contrast;
  29316. },
  29317. /**
  29318. * Sets The camera contrast used on this material.
  29319. */
  29320. set: function (value) {
  29321. this._imageProcessingConfiguration.contrast = value;
  29322. },
  29323. enumerable: true,
  29324. configurable: true
  29325. });
  29326. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  29327. /**
  29328. * Gets the Color Grading 2D Lookup Texture.
  29329. */
  29330. get: function () {
  29331. return this._imageProcessingConfiguration.colorGradingTexture;
  29332. },
  29333. /**
  29334. * Sets the Color Grading 2D Lookup Texture.
  29335. */
  29336. set: function (value) {
  29337. this._imageProcessingConfiguration.colorGradingTexture = value;
  29338. },
  29339. enumerable: true,
  29340. configurable: true
  29341. });
  29342. StandardMaterial.prototype.getClassName = function () {
  29343. return "StandardMaterial";
  29344. };
  29345. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  29346. get: function () {
  29347. return this._useLogarithmicDepth;
  29348. },
  29349. set: function (value) {
  29350. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29351. this._markAllSubMeshesAsMiscDirty();
  29352. },
  29353. enumerable: true,
  29354. configurable: true
  29355. });
  29356. StandardMaterial.prototype.needAlphaBlending = function () {
  29357. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  29358. };
  29359. StandardMaterial.prototype.needAlphaTesting = function () {
  29360. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  29361. };
  29362. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  29363. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  29364. };
  29365. StandardMaterial.prototype.getAlphaTestTexture = function () {
  29366. return this._diffuseTexture;
  29367. };
  29368. /**
  29369. * Child classes can use it to update shaders
  29370. */
  29371. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29372. if (this.isFrozen) {
  29373. if (this._wasPreviouslyReady && subMesh.effect) {
  29374. return true;
  29375. }
  29376. }
  29377. if (!subMesh._materialDefines) {
  29378. subMesh._materialDefines = new StandardMaterialDefines();
  29379. }
  29380. var scene = this.getScene();
  29381. var defines = subMesh._materialDefines;
  29382. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  29383. if (defines._renderId === scene.getRenderId()) {
  29384. return true;
  29385. }
  29386. }
  29387. var engine = scene.getEngine();
  29388. // Lights
  29389. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  29390. // Textures
  29391. if (defines._areTexturesDirty) {
  29392. defines._needUVs = false;
  29393. defines.MAINUV1 = false;
  29394. defines.MAINUV2 = false;
  29395. if (scene.texturesEnabled) {
  29396. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29397. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  29398. return false;
  29399. }
  29400. else {
  29401. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  29402. }
  29403. }
  29404. else {
  29405. defines.DIFFUSE = false;
  29406. }
  29407. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29408. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  29409. return false;
  29410. }
  29411. else {
  29412. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  29413. }
  29414. }
  29415. else {
  29416. defines.AMBIENT = false;
  29417. }
  29418. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29419. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  29420. return false;
  29421. }
  29422. else {
  29423. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  29424. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  29425. }
  29426. }
  29427. else {
  29428. defines.OPACITY = false;
  29429. }
  29430. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29431. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  29432. return false;
  29433. }
  29434. else {
  29435. defines._needNormals = true;
  29436. defines.REFLECTION = true;
  29437. defines.ROUGHNESS = (this._roughness > 0);
  29438. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  29439. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  29440. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  29441. switch (this._reflectionTexture.coordinatesMode) {
  29442. case BABYLON.Texture.CUBIC_MODE:
  29443. case BABYLON.Texture.INVCUBIC_MODE:
  29444. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  29445. break;
  29446. case BABYLON.Texture.EXPLICIT_MODE:
  29447. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  29448. break;
  29449. case BABYLON.Texture.PLANAR_MODE:
  29450. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  29451. break;
  29452. case BABYLON.Texture.PROJECTION_MODE:
  29453. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  29454. break;
  29455. case BABYLON.Texture.SKYBOX_MODE:
  29456. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  29457. break;
  29458. case BABYLON.Texture.SPHERICAL_MODE:
  29459. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  29460. break;
  29461. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29462. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  29463. break;
  29464. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29465. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  29466. break;
  29467. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  29468. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  29469. break;
  29470. }
  29471. }
  29472. }
  29473. else {
  29474. defines.REFLECTION = false;
  29475. }
  29476. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29477. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  29478. return false;
  29479. }
  29480. else {
  29481. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  29482. }
  29483. }
  29484. else {
  29485. defines.EMISSIVE = false;
  29486. }
  29487. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29488. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  29489. return false;
  29490. }
  29491. else {
  29492. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  29493. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  29494. }
  29495. }
  29496. else {
  29497. defines.LIGHTMAP = false;
  29498. }
  29499. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29500. if (!this._specularTexture.isReadyOrNotBlocking()) {
  29501. return false;
  29502. }
  29503. else {
  29504. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  29505. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  29506. }
  29507. }
  29508. else {
  29509. defines.SPECULAR = false;
  29510. }
  29511. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  29512. // Bump texure can not be not blocking.
  29513. if (!this._bumpTexture.isReady()) {
  29514. return false;
  29515. }
  29516. else {
  29517. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  29518. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  29519. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  29520. defines.PARALLAX = this._useParallax;
  29521. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  29522. }
  29523. }
  29524. else {
  29525. defines.BUMP = false;
  29526. }
  29527. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29528. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  29529. return false;
  29530. }
  29531. else {
  29532. defines._needUVs = true;
  29533. defines.REFRACTION = true;
  29534. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  29535. }
  29536. }
  29537. else {
  29538. defines.REFRACTION = false;
  29539. }
  29540. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  29541. }
  29542. else {
  29543. defines.DIFFUSE = false;
  29544. defines.AMBIENT = false;
  29545. defines.OPACITY = false;
  29546. defines.REFLECTION = false;
  29547. defines.EMISSIVE = false;
  29548. defines.LIGHTMAP = false;
  29549. defines.BUMP = false;
  29550. defines.REFRACTION = false;
  29551. }
  29552. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  29553. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  29554. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  29555. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  29556. }
  29557. if (defines._areImageProcessingDirty) {
  29558. if (!this._imageProcessingConfiguration.isReady()) {
  29559. return false;
  29560. }
  29561. this._imageProcessingConfiguration.prepareDefines(defines);
  29562. }
  29563. if (defines._areFresnelDirty) {
  29564. if (StandardMaterial.FresnelEnabled) {
  29565. // Fresnel
  29566. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  29567. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  29568. this._reflectionFresnelParameters) {
  29569. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  29570. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  29571. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  29572. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  29573. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  29574. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  29575. defines._needNormals = true;
  29576. defines.FRESNEL = true;
  29577. }
  29578. }
  29579. else {
  29580. defines.FRESNEL = false;
  29581. }
  29582. }
  29583. // Misc.
  29584. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  29585. // Attribs
  29586. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  29587. // Values that need to be evaluated on every frame
  29588. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  29589. if (scene._mirroredCameraPosition && defines.BUMP) {
  29590. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  29591. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  29592. defines.markAsUnprocessed();
  29593. }
  29594. // Get correct effect
  29595. if (defines.isDirty) {
  29596. defines.markAsProcessed();
  29597. scene.resetCachedMaterial();
  29598. // Fallbacks
  29599. var fallbacks = new BABYLON.EffectFallbacks();
  29600. if (defines.REFLECTION) {
  29601. fallbacks.addFallback(0, "REFLECTION");
  29602. }
  29603. if (defines.SPECULAR) {
  29604. fallbacks.addFallback(0, "SPECULAR");
  29605. }
  29606. if (defines.BUMP) {
  29607. fallbacks.addFallback(0, "BUMP");
  29608. }
  29609. if (defines.PARALLAX) {
  29610. fallbacks.addFallback(1, "PARALLAX");
  29611. }
  29612. if (defines.PARALLAXOCCLUSION) {
  29613. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29614. }
  29615. if (defines.SPECULAROVERALPHA) {
  29616. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29617. }
  29618. if (defines.FOG) {
  29619. fallbacks.addFallback(1, "FOG");
  29620. }
  29621. if (defines.POINTSIZE) {
  29622. fallbacks.addFallback(0, "POINTSIZE");
  29623. }
  29624. if (defines.LOGARITHMICDEPTH) {
  29625. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29626. }
  29627. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  29628. if (defines.SPECULARTERM) {
  29629. fallbacks.addFallback(0, "SPECULARTERM");
  29630. }
  29631. if (defines.DIFFUSEFRESNEL) {
  29632. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  29633. }
  29634. if (defines.OPACITYFRESNEL) {
  29635. fallbacks.addFallback(2, "OPACITYFRESNEL");
  29636. }
  29637. if (defines.REFLECTIONFRESNEL) {
  29638. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  29639. }
  29640. if (defines.EMISSIVEFRESNEL) {
  29641. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  29642. }
  29643. if (defines.FRESNEL) {
  29644. fallbacks.addFallback(4, "FRESNEL");
  29645. }
  29646. //Attributes
  29647. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29648. if (defines.NORMAL) {
  29649. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29650. }
  29651. if (defines.UV1) {
  29652. attribs.push(BABYLON.VertexBuffer.UVKind);
  29653. }
  29654. if (defines.UV2) {
  29655. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29656. }
  29657. if (defines.VERTEXCOLOR) {
  29658. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29659. }
  29660. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  29661. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  29662. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  29663. var shaderName = "default";
  29664. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  29665. "vFogInfos", "vFogColor", "pointSize",
  29666. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29667. "mBones",
  29668. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29669. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  29670. "logarithmicDepthConstant"
  29671. ];
  29672. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29673. var uniformBuffers = ["Material", "Scene"];
  29674. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  29675. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  29676. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  29677. uniformsNames: uniforms,
  29678. uniformBuffersNames: uniformBuffers,
  29679. samplers: samplers,
  29680. defines: defines,
  29681. maxSimultaneousLights: this._maxSimultaneousLights
  29682. });
  29683. if (this.customShaderNameResolve) {
  29684. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  29685. }
  29686. var join = defines.toString();
  29687. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  29688. attributes: attribs,
  29689. uniformsNames: uniforms,
  29690. uniformBuffersNames: uniformBuffers,
  29691. samplers: samplers,
  29692. defines: join,
  29693. fallbacks: fallbacks,
  29694. onCompiled: this.onCompiled,
  29695. onError: this.onError,
  29696. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  29697. }, engine), defines);
  29698. this.buildUniformLayout();
  29699. }
  29700. if (!subMesh.effect.isReady()) {
  29701. return false;
  29702. }
  29703. defines._renderId = scene.getRenderId();
  29704. this._wasPreviouslyReady = true;
  29705. return true;
  29706. };
  29707. StandardMaterial.prototype.buildUniformLayout = function () {
  29708. // Order is important !
  29709. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  29710. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  29711. this._uniformBuffer.addUniform("opacityParts", 4);
  29712. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  29713. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  29714. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  29715. this._uniformBuffer.addUniform("refractionRightColor", 4);
  29716. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  29717. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  29718. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  29719. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  29720. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  29721. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  29722. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  29723. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  29724. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  29725. this._uniformBuffer.addUniform("vBumpInfos", 3);
  29726. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  29727. this._uniformBuffer.addUniform("ambientMatrix", 16);
  29728. this._uniformBuffer.addUniform("opacityMatrix", 16);
  29729. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  29730. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  29731. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  29732. this._uniformBuffer.addUniform("specularMatrix", 16);
  29733. this._uniformBuffer.addUniform("bumpMatrix", 16);
  29734. this._uniformBuffer.addUniform("refractionMatrix", 16);
  29735. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  29736. this._uniformBuffer.addUniform("vSpecularColor", 4);
  29737. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  29738. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  29739. this._uniformBuffer.addUniform("pointSize", 1);
  29740. this._uniformBuffer.create();
  29741. };
  29742. StandardMaterial.prototype.unbind = function () {
  29743. if (this._activeEffect) {
  29744. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  29745. this._activeEffect.setTexture("reflection2DSampler", null);
  29746. }
  29747. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  29748. this._activeEffect.setTexture("refraction2DSampler", null);
  29749. }
  29750. }
  29751. _super.prototype.unbind.call(this);
  29752. };
  29753. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29754. var scene = this.getScene();
  29755. var defines = subMesh._materialDefines;
  29756. if (!defines) {
  29757. return;
  29758. }
  29759. var effect = subMesh.effect;
  29760. this._activeEffect = effect;
  29761. // Matrices
  29762. this.bindOnlyWorldMatrix(world);
  29763. // Bones
  29764. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  29765. if (this._mustRebind(scene, effect, mesh.visibility)) {
  29766. this._uniformBuffer.bindToEffect(effect, "Material");
  29767. this.bindViewProjection(effect);
  29768. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  29769. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  29770. // Fresnel
  29771. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29772. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  29773. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  29774. }
  29775. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29776. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29777. }
  29778. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29779. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  29780. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  29781. }
  29782. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29783. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  29784. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  29785. }
  29786. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29787. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29788. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29789. }
  29790. }
  29791. // Textures
  29792. if (scene.texturesEnabled) {
  29793. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29794. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  29795. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  29796. }
  29797. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29798. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  29799. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  29800. }
  29801. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29802. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  29803. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  29804. }
  29805. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29806. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  29807. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  29808. }
  29809. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29810. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  29811. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  29812. }
  29813. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29814. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  29815. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  29816. }
  29817. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29818. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  29819. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  29820. }
  29821. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29822. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  29823. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  29824. }
  29825. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29826. var depth = 1.0;
  29827. if (!this._refractionTexture.isCube) {
  29828. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  29829. if (this._refractionTexture.depth) {
  29830. depth = this._refractionTexture.depth;
  29831. }
  29832. }
  29833. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29834. }
  29835. }
  29836. // Point size
  29837. if (this.pointsCloud) {
  29838. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  29839. }
  29840. if (defines.SPECULARTERM) {
  29841. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  29842. }
  29843. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  29844. // Diffuse
  29845. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  29846. }
  29847. // Textures
  29848. if (scene.texturesEnabled) {
  29849. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29850. effect.setTexture("diffuseSampler", this._diffuseTexture);
  29851. }
  29852. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29853. effect.setTexture("ambientSampler", this._ambientTexture);
  29854. }
  29855. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29856. effect.setTexture("opacitySampler", this._opacityTexture);
  29857. }
  29858. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29859. if (this._reflectionTexture.isCube) {
  29860. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  29861. }
  29862. else {
  29863. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  29864. }
  29865. }
  29866. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29867. effect.setTexture("emissiveSampler", this._emissiveTexture);
  29868. }
  29869. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29870. effect.setTexture("lightmapSampler", this._lightmapTexture);
  29871. }
  29872. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29873. effect.setTexture("specularSampler", this._specularTexture);
  29874. }
  29875. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29876. effect.setTexture("bumpSampler", this._bumpTexture);
  29877. }
  29878. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29879. var depth = 1.0;
  29880. if (this._refractionTexture.isCube) {
  29881. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  29882. }
  29883. else {
  29884. effect.setTexture("refraction2DSampler", this._refractionTexture);
  29885. }
  29886. }
  29887. }
  29888. // Clip plane
  29889. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  29890. // Colors
  29891. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29892. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  29893. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29894. }
  29895. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  29896. // Lights
  29897. if (scene.lightsEnabled && !this._disableLighting) {
  29898. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  29899. }
  29900. // View
  29901. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  29902. this.bindView(effect);
  29903. }
  29904. // Fog
  29905. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  29906. // Morph targets
  29907. if (defines.NUM_MORPH_INFLUENCERS) {
  29908. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  29909. }
  29910. // Log. depth
  29911. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  29912. // image processing
  29913. this._imageProcessingConfiguration.bind(this._activeEffect);
  29914. }
  29915. this._uniformBuffer.update();
  29916. this._afterBind(mesh, this._activeEffect);
  29917. };
  29918. StandardMaterial.prototype.getAnimatables = function () {
  29919. var results = [];
  29920. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  29921. results.push(this._diffuseTexture);
  29922. }
  29923. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  29924. results.push(this._ambientTexture);
  29925. }
  29926. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  29927. results.push(this._opacityTexture);
  29928. }
  29929. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  29930. results.push(this._reflectionTexture);
  29931. }
  29932. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  29933. results.push(this._emissiveTexture);
  29934. }
  29935. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  29936. results.push(this._specularTexture);
  29937. }
  29938. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  29939. results.push(this._bumpTexture);
  29940. }
  29941. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  29942. results.push(this._lightmapTexture);
  29943. }
  29944. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  29945. results.push(this._refractionTexture);
  29946. }
  29947. return results;
  29948. };
  29949. StandardMaterial.prototype.getActiveTextures = function () {
  29950. var activeTextures = _super.prototype.getActiveTextures.call(this);
  29951. if (this._diffuseTexture) {
  29952. activeTextures.push(this._diffuseTexture);
  29953. }
  29954. if (this._ambientTexture) {
  29955. activeTextures.push(this._ambientTexture);
  29956. }
  29957. if (this._opacityTexture) {
  29958. activeTextures.push(this._opacityTexture);
  29959. }
  29960. if (this._reflectionTexture) {
  29961. activeTextures.push(this._reflectionTexture);
  29962. }
  29963. if (this._emissiveTexture) {
  29964. activeTextures.push(this._emissiveTexture);
  29965. }
  29966. if (this._specularTexture) {
  29967. activeTextures.push(this._specularTexture);
  29968. }
  29969. if (this._bumpTexture) {
  29970. activeTextures.push(this._bumpTexture);
  29971. }
  29972. if (this._lightmapTexture) {
  29973. activeTextures.push(this._lightmapTexture);
  29974. }
  29975. if (this._refractionTexture) {
  29976. activeTextures.push(this._refractionTexture);
  29977. }
  29978. return activeTextures;
  29979. };
  29980. StandardMaterial.prototype.hasTexture = function (texture) {
  29981. if (_super.prototype.hasTexture.call(this, texture)) {
  29982. return true;
  29983. }
  29984. if (this._diffuseTexture === texture) {
  29985. return true;
  29986. }
  29987. if (this._ambientTexture === texture) {
  29988. return true;
  29989. }
  29990. if (this._opacityTexture === texture) {
  29991. return true;
  29992. }
  29993. if (this._reflectionTexture === texture) {
  29994. return true;
  29995. }
  29996. if (this._emissiveTexture === texture) {
  29997. return true;
  29998. }
  29999. if (this._specularTexture === texture) {
  30000. return true;
  30001. }
  30002. if (this._bumpTexture === texture) {
  30003. return true;
  30004. }
  30005. if (this._lightmapTexture === texture) {
  30006. return true;
  30007. }
  30008. if (this._refractionTexture === texture) {
  30009. return true;
  30010. }
  30011. return false;
  30012. };
  30013. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30014. if (forceDisposeTextures) {
  30015. if (this._diffuseTexture) {
  30016. this._diffuseTexture.dispose();
  30017. }
  30018. if (this._ambientTexture) {
  30019. this._ambientTexture.dispose();
  30020. }
  30021. if (this._opacityTexture) {
  30022. this._opacityTexture.dispose();
  30023. }
  30024. if (this._reflectionTexture) {
  30025. this._reflectionTexture.dispose();
  30026. }
  30027. if (this._emissiveTexture) {
  30028. this._emissiveTexture.dispose();
  30029. }
  30030. if (this._specularTexture) {
  30031. this._specularTexture.dispose();
  30032. }
  30033. if (this._bumpTexture) {
  30034. this._bumpTexture.dispose();
  30035. }
  30036. if (this._lightmapTexture) {
  30037. this._lightmapTexture.dispose();
  30038. }
  30039. if (this._refractionTexture) {
  30040. this._refractionTexture.dispose();
  30041. }
  30042. }
  30043. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30044. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30045. }
  30046. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30047. };
  30048. StandardMaterial.prototype.clone = function (name) {
  30049. var _this = this;
  30050. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  30051. result.name = name;
  30052. result.id = name;
  30053. return result;
  30054. };
  30055. StandardMaterial.prototype.serialize = function () {
  30056. return BABYLON.SerializationHelper.Serialize(this);
  30057. };
  30058. // Statics
  30059. StandardMaterial.Parse = function (source, scene, rootUrl) {
  30060. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  30061. };
  30062. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  30063. get: function () {
  30064. return StandardMaterial._DiffuseTextureEnabled;
  30065. },
  30066. set: function (value) {
  30067. if (StandardMaterial._DiffuseTextureEnabled === value) {
  30068. return;
  30069. }
  30070. StandardMaterial._DiffuseTextureEnabled = value;
  30071. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30072. },
  30073. enumerable: true,
  30074. configurable: true
  30075. });
  30076. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  30077. get: function () {
  30078. return StandardMaterial._AmbientTextureEnabled;
  30079. },
  30080. set: function (value) {
  30081. if (StandardMaterial._AmbientTextureEnabled === value) {
  30082. return;
  30083. }
  30084. StandardMaterial._AmbientTextureEnabled = value;
  30085. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30086. },
  30087. enumerable: true,
  30088. configurable: true
  30089. });
  30090. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  30091. get: function () {
  30092. return StandardMaterial._OpacityTextureEnabled;
  30093. },
  30094. set: function (value) {
  30095. if (StandardMaterial._OpacityTextureEnabled === value) {
  30096. return;
  30097. }
  30098. StandardMaterial._OpacityTextureEnabled = value;
  30099. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30100. },
  30101. enumerable: true,
  30102. configurable: true
  30103. });
  30104. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  30105. get: function () {
  30106. return StandardMaterial._ReflectionTextureEnabled;
  30107. },
  30108. set: function (value) {
  30109. if (StandardMaterial._ReflectionTextureEnabled === value) {
  30110. return;
  30111. }
  30112. StandardMaterial._ReflectionTextureEnabled = value;
  30113. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30114. },
  30115. enumerable: true,
  30116. configurable: true
  30117. });
  30118. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  30119. get: function () {
  30120. return StandardMaterial._EmissiveTextureEnabled;
  30121. },
  30122. set: function (value) {
  30123. if (StandardMaterial._EmissiveTextureEnabled === value) {
  30124. return;
  30125. }
  30126. StandardMaterial._EmissiveTextureEnabled = value;
  30127. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30128. },
  30129. enumerable: true,
  30130. configurable: true
  30131. });
  30132. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  30133. get: function () {
  30134. return StandardMaterial._SpecularTextureEnabled;
  30135. },
  30136. set: function (value) {
  30137. if (StandardMaterial._SpecularTextureEnabled === value) {
  30138. return;
  30139. }
  30140. StandardMaterial._SpecularTextureEnabled = value;
  30141. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30142. },
  30143. enumerable: true,
  30144. configurable: true
  30145. });
  30146. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  30147. get: function () {
  30148. return StandardMaterial._BumpTextureEnabled;
  30149. },
  30150. set: function (value) {
  30151. if (StandardMaterial._BumpTextureEnabled === value) {
  30152. return;
  30153. }
  30154. StandardMaterial._BumpTextureEnabled = value;
  30155. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30156. },
  30157. enumerable: true,
  30158. configurable: true
  30159. });
  30160. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  30161. get: function () {
  30162. return StandardMaterial._LightmapTextureEnabled;
  30163. },
  30164. set: function (value) {
  30165. if (StandardMaterial._LightmapTextureEnabled === value) {
  30166. return;
  30167. }
  30168. StandardMaterial._LightmapTextureEnabled = value;
  30169. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30170. },
  30171. enumerable: true,
  30172. configurable: true
  30173. });
  30174. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  30175. get: function () {
  30176. return StandardMaterial._RefractionTextureEnabled;
  30177. },
  30178. set: function (value) {
  30179. if (StandardMaterial._RefractionTextureEnabled === value) {
  30180. return;
  30181. }
  30182. StandardMaterial._RefractionTextureEnabled = value;
  30183. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30184. },
  30185. enumerable: true,
  30186. configurable: true
  30187. });
  30188. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  30189. get: function () {
  30190. return StandardMaterial._ColorGradingTextureEnabled;
  30191. },
  30192. set: function (value) {
  30193. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  30194. return;
  30195. }
  30196. StandardMaterial._ColorGradingTextureEnabled = value;
  30197. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30198. },
  30199. enumerable: true,
  30200. configurable: true
  30201. });
  30202. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  30203. get: function () {
  30204. return StandardMaterial._FresnelEnabled;
  30205. },
  30206. set: function (value) {
  30207. if (StandardMaterial._FresnelEnabled === value) {
  30208. return;
  30209. }
  30210. StandardMaterial._FresnelEnabled = value;
  30211. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  30212. },
  30213. enumerable: true,
  30214. configurable: true
  30215. });
  30216. return StandardMaterial;
  30217. }(BABYLON.PushMaterial));
  30218. // Flags used to enable or disable a type of texture for all Standard Materials
  30219. StandardMaterial._DiffuseTextureEnabled = true;
  30220. StandardMaterial._AmbientTextureEnabled = true;
  30221. StandardMaterial._OpacityTextureEnabled = true;
  30222. StandardMaterial._ReflectionTextureEnabled = true;
  30223. StandardMaterial._EmissiveTextureEnabled = true;
  30224. StandardMaterial._SpecularTextureEnabled = true;
  30225. StandardMaterial._BumpTextureEnabled = true;
  30226. StandardMaterial._LightmapTextureEnabled = true;
  30227. StandardMaterial._RefractionTextureEnabled = true;
  30228. StandardMaterial._ColorGradingTextureEnabled = true;
  30229. StandardMaterial._FresnelEnabled = true;
  30230. __decorate([
  30231. BABYLON.serializeAsTexture("diffuseTexture")
  30232. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  30233. __decorate([
  30234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30235. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  30236. __decorate([
  30237. BABYLON.serializeAsTexture("ambientTexture")
  30238. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  30239. __decorate([
  30240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30241. ], StandardMaterial.prototype, "ambientTexture", void 0);
  30242. __decorate([
  30243. BABYLON.serializeAsTexture("opacityTexture")
  30244. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  30245. __decorate([
  30246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30247. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30248. __decorate([
  30249. BABYLON.serializeAsTexture("reflectionTexture")
  30250. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  30251. __decorate([
  30252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30253. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30254. __decorate([
  30255. BABYLON.serializeAsTexture("emissiveTexture")
  30256. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  30257. __decorate([
  30258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30259. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30260. __decorate([
  30261. BABYLON.serializeAsTexture("specularTexture")
  30262. ], StandardMaterial.prototype, "_specularTexture", void 0);
  30263. __decorate([
  30264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30265. ], StandardMaterial.prototype, "specularTexture", void 0);
  30266. __decorate([
  30267. BABYLON.serializeAsTexture("bumpTexture")
  30268. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  30269. __decorate([
  30270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30271. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30272. __decorate([
  30273. BABYLON.serializeAsTexture("lightmapTexture")
  30274. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  30275. __decorate([
  30276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30277. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30278. __decorate([
  30279. BABYLON.serializeAsTexture("refractionTexture")
  30280. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  30281. __decorate([
  30282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30283. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30284. __decorate([
  30285. BABYLON.serializeAsColor3("ambient")
  30286. ], StandardMaterial.prototype, "ambientColor", void 0);
  30287. __decorate([
  30288. BABYLON.serializeAsColor3("diffuse")
  30289. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30290. __decorate([
  30291. BABYLON.serializeAsColor3("specular")
  30292. ], StandardMaterial.prototype, "specularColor", void 0);
  30293. __decorate([
  30294. BABYLON.serializeAsColor3("emissive")
  30295. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30296. __decorate([
  30297. BABYLON.serialize()
  30298. ], StandardMaterial.prototype, "specularPower", void 0);
  30299. __decorate([
  30300. BABYLON.serialize("useAlphaFromDiffuseTexture")
  30301. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  30302. __decorate([
  30303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30304. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30305. __decorate([
  30306. BABYLON.serialize("useEmissiveAsIllumination")
  30307. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  30308. __decorate([
  30309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30310. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30311. __decorate([
  30312. BABYLON.serialize("linkEmissiveWithDiffuse")
  30313. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  30314. __decorate([
  30315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30316. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30317. __decorate([
  30318. BABYLON.serialize("useSpecularOverAlpha")
  30319. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  30320. __decorate([
  30321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30322. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30323. __decorate([
  30324. BABYLON.serialize("useReflectionOverAlpha")
  30325. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  30326. __decorate([
  30327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30328. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30329. __decorate([
  30330. BABYLON.serialize("disableLighting")
  30331. ], StandardMaterial.prototype, "_disableLighting", void 0);
  30332. __decorate([
  30333. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30334. ], StandardMaterial.prototype, "disableLighting", void 0);
  30335. __decorate([
  30336. BABYLON.serialize("useParallax")
  30337. ], StandardMaterial.prototype, "_useParallax", void 0);
  30338. __decorate([
  30339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30340. ], StandardMaterial.prototype, "useParallax", void 0);
  30341. __decorate([
  30342. BABYLON.serialize("useParallaxOcclusion")
  30343. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  30344. __decorate([
  30345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30346. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30347. __decorate([
  30348. BABYLON.serialize()
  30349. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30350. __decorate([
  30351. BABYLON.serialize("roughness")
  30352. ], StandardMaterial.prototype, "_roughness", void 0);
  30353. __decorate([
  30354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30355. ], StandardMaterial.prototype, "roughness", void 0);
  30356. __decorate([
  30357. BABYLON.serialize()
  30358. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30359. __decorate([
  30360. BABYLON.serialize()
  30361. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30362. __decorate([
  30363. BABYLON.serialize("useLightmapAsShadowmap")
  30364. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  30365. __decorate([
  30366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30367. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30368. __decorate([
  30369. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  30370. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  30371. __decorate([
  30372. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30373. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30374. __decorate([
  30375. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  30376. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  30377. __decorate([
  30378. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30379. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30380. __decorate([
  30381. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  30382. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  30383. __decorate([
  30384. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30385. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30386. __decorate([
  30387. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  30388. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  30389. __decorate([
  30390. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30391. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30392. __decorate([
  30393. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  30394. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  30395. __decorate([
  30396. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30397. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30398. __decorate([
  30399. BABYLON.serialize("useReflectionFresnelFromSpecular")
  30400. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  30401. __decorate([
  30402. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30403. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30404. __decorate([
  30405. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  30406. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  30407. __decorate([
  30408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30409. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30410. __decorate([
  30411. BABYLON.serialize("maxSimultaneousLights")
  30412. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  30413. __decorate([
  30414. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30415. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30416. __decorate([
  30417. BABYLON.serialize("invertNormalMapX")
  30418. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  30419. __decorate([
  30420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30421. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30422. __decorate([
  30423. BABYLON.serialize("invertNormalMapY")
  30424. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  30425. __decorate([
  30426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30427. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30428. __decorate([
  30429. BABYLON.serialize("twoSidedLighting")
  30430. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  30431. __decorate([
  30432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30433. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  30434. __decorate([
  30435. BABYLON.serialize()
  30436. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30437. BABYLON.StandardMaterial = StandardMaterial;
  30438. })(BABYLON || (BABYLON = {}));
  30439. //# sourceMappingURL=babylon.standardMaterial.js.map
  30440. var BABYLON;
  30441. (function (BABYLON) {
  30442. var PBRMaterialDefines = (function (_super) {
  30443. __extends(PBRMaterialDefines, _super);
  30444. function PBRMaterialDefines() {
  30445. var _this = _super.call(this) || this;
  30446. _this.PBR = true;
  30447. _this.MAINUV1 = false;
  30448. _this.MAINUV2 = false;
  30449. _this.UV1 = false;
  30450. _this.UV2 = false;
  30451. _this.ALBEDO = false;
  30452. _this.ALBEDODIRECTUV = 0;
  30453. _this.VERTEXCOLOR = false;
  30454. _this.AMBIENT = false;
  30455. _this.AMBIENTDIRECTUV = 0;
  30456. _this.AMBIENTINGRAYSCALE = false;
  30457. _this.OPACITY = false;
  30458. _this.VERTEXALPHA = false;
  30459. _this.OPACITYDIRECTUV = 0;
  30460. _this.OPACITYRGB = false;
  30461. _this.ALPHATEST = false;
  30462. _this.ALPHABLEND = false;
  30463. _this.ALPHAFROMALBEDO = false;
  30464. _this.ALPHATESTVALUE = 0.5;
  30465. _this.SPECULAROVERALPHA = false;
  30466. _this.RADIANCEOVERALPHA = false;
  30467. _this.ALPHAFRESNEL = false;
  30468. _this.PREMULTIPLYALPHA = false;
  30469. _this.EMISSIVE = false;
  30470. _this.EMISSIVEDIRECTUV = 0;
  30471. _this.REFLECTIVITY = false;
  30472. _this.REFLECTIVITYDIRECTUV = 0;
  30473. _this.SPECULARTERM = false;
  30474. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  30475. _this.MICROSURFACEAUTOMATIC = false;
  30476. _this.LODBASEDMICROSFURACE = false;
  30477. _this.MICROSURFACEMAP = false;
  30478. _this.MICROSURFACEMAPDIRECTUV = 0;
  30479. _this.METALLICWORKFLOW = false;
  30480. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  30481. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  30482. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  30483. _this.AOSTOREINMETALMAPRED = false;
  30484. _this.ENVIRONMENTBRDF = false;
  30485. _this.NORMAL = false;
  30486. _this.TANGENT = false;
  30487. _this.BUMP = false;
  30488. _this.BUMPDIRECTUV = 0;
  30489. _this.PARALLAX = false;
  30490. _this.PARALLAXOCCLUSION = false;
  30491. _this.INVERTNORMALMAPX = false;
  30492. _this.INVERTNORMALMAPY = false;
  30493. _this.NORMALXYSCALE = true;
  30494. _this.LIGHTMAP = false;
  30495. _this.LIGHTMAPDIRECTUV = 0;
  30496. _this.USELIGHTMAPASSHADOWMAP = false;
  30497. _this.REFLECTION = false;
  30498. _this.REFLECTIONMAP_3D = false;
  30499. _this.REFLECTIONMAP_SPHERICAL = false;
  30500. _this.REFLECTIONMAP_PLANAR = false;
  30501. _this.REFLECTIONMAP_CUBIC = false;
  30502. _this.REFLECTIONMAP_PROJECTION = false;
  30503. _this.REFLECTIONMAP_SKYBOX = false;
  30504. _this.REFLECTIONMAP_EXPLICIT = false;
  30505. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30506. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30507. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30508. _this.INVERTCUBICMAP = false;
  30509. _this.USESPHERICALFROMREFLECTIONMAP = false;
  30510. _this.USESPHERICALINFRAGMENT = false;
  30511. _this.REFLECTIONMAP_OPPOSITEZ = false;
  30512. _this.LODINREFLECTIONALPHA = false;
  30513. _this.GAMMAREFLECTION = false;
  30514. _this.REFRACTION = false;
  30515. _this.REFRACTIONMAP_3D = false;
  30516. _this.REFRACTIONMAP_OPPOSITEZ = false;
  30517. _this.LODINREFRACTIONALPHA = false;
  30518. _this.GAMMAREFRACTION = false;
  30519. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  30520. _this.INSTANCES = false;
  30521. _this.NUM_BONE_INFLUENCERS = 0;
  30522. _this.BonesPerMesh = 0;
  30523. _this.MORPHTARGETS = false;
  30524. _this.MORPHTARGETS_NORMAL = false;
  30525. _this.MORPHTARGETS_TANGENT = false;
  30526. _this.NUM_MORPH_INFLUENCERS = 0;
  30527. _this.IMAGEPROCESSING = false;
  30528. _this.VIGNETTE = false;
  30529. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30530. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30531. _this.TONEMAPPING = false;
  30532. _this.CONTRAST = false;
  30533. _this.COLORCURVES = false;
  30534. _this.COLORGRADING = false;
  30535. _this.SAMPLER3DGREENDEPTH = false;
  30536. _this.SAMPLER3DBGRMAP = false;
  30537. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30538. _this.EXPOSURE = false;
  30539. _this.USEPHYSICALLIGHTFALLOFF = false;
  30540. _this.TWOSIDEDLIGHTING = false;
  30541. _this.SHADOWFLOAT = false;
  30542. _this.USERIGHTHANDEDSYSTEM = false;
  30543. _this.CLIPPLANE = false;
  30544. _this.POINTSIZE = false;
  30545. _this.FOG = false;
  30546. _this.LOGARITHMICDEPTH = false;
  30547. _this.rebuild();
  30548. return _this;
  30549. }
  30550. PBRMaterialDefines.prototype.reset = function () {
  30551. _super.prototype.reset.call(this);
  30552. this.ALPHATESTVALUE = 0.5;
  30553. this.PBR = true;
  30554. };
  30555. return PBRMaterialDefines;
  30556. }(BABYLON.MaterialDefines));
  30557. /**
  30558. * The Physically based material base class of BJS.
  30559. *
  30560. * This offers the main features of a standard PBR material.
  30561. * For more information, please refer to the documentation :
  30562. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  30563. */
  30564. var PBRBaseMaterial = (function (_super) {
  30565. __extends(PBRBaseMaterial, _super);
  30566. /**
  30567. * Instantiates a new PBRMaterial instance.
  30568. *
  30569. * @param name The material name
  30570. * @param scene The scene the material will be use in.
  30571. */
  30572. function PBRBaseMaterial(name, scene) {
  30573. var _this = _super.call(this, name, scene) || this;
  30574. /**
  30575. * Intensity of the direct lights e.g. the four lights available in your scene.
  30576. * This impacts both the direct diffuse and specular highlights.
  30577. */
  30578. _this._directIntensity = 1.0;
  30579. /**
  30580. * Intensity of the emissive part of the material.
  30581. * This helps controlling the emissive effect without modifying the emissive color.
  30582. */
  30583. _this._emissiveIntensity = 1.0;
  30584. /**
  30585. * Intensity of the environment e.g. how much the environment will light the object
  30586. * either through harmonics for rough material or through the refelction for shiny ones.
  30587. */
  30588. _this._environmentIntensity = 1.0;
  30589. /**
  30590. * This is a special control allowing the reduction of the specular highlights coming from the
  30591. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  30592. */
  30593. _this._specularIntensity = 1.0;
  30594. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  30595. /**
  30596. * Debug Control allowing disabling the bump map on this material.
  30597. */
  30598. _this._disableBumpMap = false;
  30599. /**
  30600. * AKA Occlusion Texture Intensity in other nomenclature.
  30601. */
  30602. _this._ambientTextureStrength = 1.0;
  30603. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  30604. /**
  30605. * AKA Diffuse Color in other nomenclature.
  30606. */
  30607. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  30608. /**
  30609. * AKA Specular Color in other nomenclature.
  30610. */
  30611. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  30612. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  30613. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  30614. /**
  30615. * AKA Glossiness in other nomenclature.
  30616. */
  30617. _this._microSurface = 0.9;
  30618. /**
  30619. * source material index of refraction (IOR)' / 'destination material IOR.
  30620. */
  30621. _this._indexOfRefraction = 0.66;
  30622. /**
  30623. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  30624. */
  30625. _this._invertRefractionY = false;
  30626. /**
  30627. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  30628. * Materials half opaque for instance using refraction could benefit from this control.
  30629. */
  30630. _this._linkRefractionWithTransparency = false;
  30631. _this._useLightmapAsShadowmap = false;
  30632. /**
  30633. * Specifies that the alpha is coming form the albedo channel alpha channel.
  30634. */
  30635. _this._useAlphaFromAlbedoTexture = false;
  30636. /**
  30637. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  30638. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  30639. */
  30640. _this._useSpecularOverAlpha = true;
  30641. /**
  30642. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  30643. */
  30644. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  30645. /**
  30646. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  30647. */
  30648. _this._useRoughnessFromMetallicTextureAlpha = true;
  30649. /**
  30650. * Specifies if the metallic texture contains the roughness information in its green channel.
  30651. */
  30652. _this._useRoughnessFromMetallicTextureGreen = false;
  30653. /**
  30654. * Specifies if the metallic texture contains the metallness information in its blue channel.
  30655. */
  30656. _this._useMetallnessFromMetallicTextureBlue = false;
  30657. /**
  30658. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  30659. */
  30660. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  30661. /**
  30662. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  30663. */
  30664. _this._useAmbientInGrayScale = false;
  30665. /**
  30666. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  30667. * The material will try to infer what glossiness each pixel should be.
  30668. */
  30669. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  30670. /**
  30671. * BJS is using an harcoded light falloff based on a manually sets up range.
  30672. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  30673. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  30674. */
  30675. _this._usePhysicalLightFalloff = true;
  30676. /**
  30677. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  30678. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  30679. */
  30680. _this._useRadianceOverAlpha = true;
  30681. /**
  30682. * Allows using the bump map in parallax mode.
  30683. */
  30684. _this._useParallax = false;
  30685. /**
  30686. * Allows using the bump map in parallax occlusion mode.
  30687. */
  30688. _this._useParallaxOcclusion = false;
  30689. /**
  30690. * Controls the scale bias of the parallax mode.
  30691. */
  30692. _this._parallaxScaleBias = 0.05;
  30693. /**
  30694. * If sets to true, disables all the lights affecting the material.
  30695. */
  30696. _this._disableLighting = false;
  30697. /**
  30698. * Number of Simultaneous lights allowed on the material.
  30699. */
  30700. _this._maxSimultaneousLights = 4;
  30701. /**
  30702. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30703. */
  30704. _this._invertNormalMapX = false;
  30705. /**
  30706. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30707. */
  30708. _this._invertNormalMapY = false;
  30709. /**
  30710. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30711. */
  30712. _this._twoSidedLighting = false;
  30713. /**
  30714. * Defines the alpha limits in alpha test mode.
  30715. */
  30716. _this._alphaCutOff = 0.4;
  30717. /**
  30718. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  30719. */
  30720. _this._forceAlphaTest = false;
  30721. /**
  30722. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  30723. * in your scene composition.
  30724. */
  30725. _this._preMultiplyAlpha = false;
  30726. /**
  30727. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  30728. * And/Or occlude the blended part.
  30729. */
  30730. _this._useAlphaFresnel = false;
  30731. /**
  30732. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  30733. * from cos thetav and roughness:
  30734. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  30735. */
  30736. _this._environmentBRDFTexture = null;
  30737. /**
  30738. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  30739. */
  30740. _this._forceIrradianceInFragment = false;
  30741. _this._renderTargets = new BABYLON.SmartArray(16);
  30742. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30743. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30744. _this._tempColor = new BABYLON.Color3();
  30745. // Setup the default processing configuration to the scene.
  30746. _this._attachImageProcessingConfiguration(null);
  30747. _this.getRenderTargetTextures = function () {
  30748. _this._renderTargets.reset();
  30749. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30750. _this._renderTargets.push(_this._reflectionTexture);
  30751. }
  30752. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30753. _this._renderTargets.push(_this._refractionTexture);
  30754. }
  30755. return _this._renderTargets;
  30756. };
  30757. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  30758. return _this;
  30759. }
  30760. /**
  30761. * Attaches a new image processing configuration to the PBR Material.
  30762. * @param configuration
  30763. */
  30764. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30765. var _this = this;
  30766. if (configuration === this._imageProcessingConfiguration) {
  30767. return;
  30768. }
  30769. // Detaches observer.
  30770. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30771. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30772. }
  30773. // Pick the scene configuration if needed.
  30774. if (!configuration) {
  30775. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30776. }
  30777. else {
  30778. this._imageProcessingConfiguration = configuration;
  30779. }
  30780. // Attaches observer.
  30781. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30782. _this._markAllSubMeshesAsImageProcessingDirty();
  30783. });
  30784. };
  30785. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  30786. get: function () {
  30787. return this._useLogarithmicDepth;
  30788. },
  30789. set: function (value) {
  30790. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30791. },
  30792. enumerable: true,
  30793. configurable: true
  30794. });
  30795. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  30796. if (this._linkRefractionWithTransparency) {
  30797. return false;
  30798. }
  30799. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  30800. };
  30801. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  30802. if (this._forceAlphaTest) {
  30803. return true;
  30804. }
  30805. if (this._linkRefractionWithTransparency) {
  30806. return false;
  30807. }
  30808. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  30809. };
  30810. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30811. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  30812. };
  30813. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  30814. return this._albedoTexture;
  30815. };
  30816. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30817. if (this.isFrozen) {
  30818. if (this._wasPreviouslyReady) {
  30819. return true;
  30820. }
  30821. }
  30822. if (!subMesh._materialDefines) {
  30823. subMesh._materialDefines = new PBRMaterialDefines();
  30824. }
  30825. var scene = this.getScene();
  30826. var defines = subMesh._materialDefines;
  30827. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30828. if (defines._renderId === scene.getRenderId()) {
  30829. return true;
  30830. }
  30831. }
  30832. var engine = scene.getEngine();
  30833. // Lights
  30834. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30835. defines._needNormals = true;
  30836. // Textures
  30837. if (defines._areTexturesDirty) {
  30838. defines._needUVs = false;
  30839. if (scene.texturesEnabled) {
  30840. if (scene.getEngine().getCaps().textureLOD) {
  30841. defines.LODBASEDMICROSFURACE = true;
  30842. }
  30843. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30844. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  30845. return false;
  30846. }
  30847. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  30848. }
  30849. else {
  30850. defines.ALBEDO = false;
  30851. }
  30852. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30853. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30854. return false;
  30855. }
  30856. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  30857. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  30858. }
  30859. else {
  30860. defines.AMBIENT = false;
  30861. }
  30862. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30863. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30864. return false;
  30865. }
  30866. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  30867. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  30868. }
  30869. else {
  30870. defines.OPACITY = false;
  30871. }
  30872. var reflectionTexture = this._getReflectionTexture();
  30873. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30874. if (!reflectionTexture.isReadyOrNotBlocking()) {
  30875. return false;
  30876. }
  30877. defines.REFLECTION = true;
  30878. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  30879. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  30880. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  30881. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  30882. defines.INVERTCUBICMAP = true;
  30883. }
  30884. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  30885. switch (reflectionTexture.coordinatesMode) {
  30886. case BABYLON.Texture.CUBIC_MODE:
  30887. case BABYLON.Texture.INVCUBIC_MODE:
  30888. defines.REFLECTIONMAP_CUBIC = true;
  30889. break;
  30890. case BABYLON.Texture.EXPLICIT_MODE:
  30891. defines.REFLECTIONMAP_EXPLICIT = true;
  30892. break;
  30893. case BABYLON.Texture.PLANAR_MODE:
  30894. defines.REFLECTIONMAP_PLANAR = true;
  30895. break;
  30896. case BABYLON.Texture.PROJECTION_MODE:
  30897. defines.REFLECTIONMAP_PROJECTION = true;
  30898. break;
  30899. case BABYLON.Texture.SKYBOX_MODE:
  30900. defines.REFLECTIONMAP_SKYBOX = true;
  30901. break;
  30902. case BABYLON.Texture.SPHERICAL_MODE:
  30903. defines.REFLECTIONMAP_SPHERICAL = true;
  30904. break;
  30905. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30906. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  30907. break;
  30908. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30909. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  30910. break;
  30911. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30912. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  30913. break;
  30914. }
  30915. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  30916. if (reflectionTexture.sphericalPolynomial) {
  30917. defines.USESPHERICALFROMREFLECTIONMAP = true;
  30918. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  30919. defines.USESPHERICALINFRAGMENT = true;
  30920. }
  30921. }
  30922. }
  30923. }
  30924. else {
  30925. defines.REFLECTION = false;
  30926. defines.REFLECTIONMAP_3D = false;
  30927. defines.REFLECTIONMAP_SPHERICAL = false;
  30928. defines.REFLECTIONMAP_PLANAR = false;
  30929. defines.REFLECTIONMAP_CUBIC = false;
  30930. defines.REFLECTIONMAP_PROJECTION = false;
  30931. defines.REFLECTIONMAP_SKYBOX = false;
  30932. defines.REFLECTIONMAP_EXPLICIT = false;
  30933. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30934. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30935. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30936. defines.INVERTCUBICMAP = false;
  30937. defines.USESPHERICALFROMREFLECTIONMAP = false;
  30938. defines.USESPHERICALINFRAGMENT = false;
  30939. defines.REFLECTIONMAP_OPPOSITEZ = false;
  30940. defines.LODINREFLECTIONALPHA = false;
  30941. defines.GAMMAREFLECTION = false;
  30942. }
  30943. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30944. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30945. return false;
  30946. }
  30947. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  30948. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30949. }
  30950. else {
  30951. defines.LIGHTMAP = false;
  30952. }
  30953. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30954. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30955. return false;
  30956. }
  30957. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  30958. }
  30959. else {
  30960. defines.EMISSIVE = false;
  30961. }
  30962. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30963. if (this._metallicTexture) {
  30964. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  30965. return false;
  30966. }
  30967. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  30968. defines.METALLICWORKFLOW = true;
  30969. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  30970. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  30971. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  30972. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  30973. }
  30974. else if (this._reflectivityTexture) {
  30975. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  30976. return false;
  30977. }
  30978. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  30979. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  30980. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  30981. }
  30982. else {
  30983. defines.REFLECTIVITY = false;
  30984. }
  30985. if (this._microSurfaceTexture) {
  30986. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  30987. return false;
  30988. }
  30989. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  30990. }
  30991. else {
  30992. defines.MICROSURFACEMAP = false;
  30993. }
  30994. }
  30995. else {
  30996. defines.REFLECTIVITY = false;
  30997. defines.MICROSURFACEMAP = false;
  30998. }
  30999. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31000. // Bump texure can not be none blocking.
  31001. if (!this._bumpTexture.isReady()) {
  31002. return false;
  31003. }
  31004. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  31005. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31006. defines.PARALLAX = true;
  31007. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  31008. }
  31009. else {
  31010. defines.PARALLAX = false;
  31011. }
  31012. defines.INVERTNORMALMAPX = !!this._invertNormalMapX;
  31013. defines.INVERTNORMALMAPY = !!this._invertNormalMapY;
  31014. if (scene._mirroredCameraPosition) {
  31015. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  31016. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  31017. }
  31018. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  31019. }
  31020. else {
  31021. defines.BUMP = false;
  31022. }
  31023. var refractionTexture = this._getRefractionTexture();
  31024. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31025. if (!refractionTexture.isReadyOrNotBlocking()) {
  31026. return false;
  31027. }
  31028. defines.REFRACTION = true;
  31029. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  31030. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  31031. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  31032. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  31033. if (this._linkRefractionWithTransparency) {
  31034. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  31035. }
  31036. }
  31037. else {
  31038. defines.REFRACTION = false;
  31039. }
  31040. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31041. // This is blocking.
  31042. if (!this._environmentBRDFTexture.isReady()) {
  31043. return false;
  31044. }
  31045. defines.ENVIRONMENTBRDF = true;
  31046. }
  31047. if (this._shouldUseAlphaFromAlbedoTexture()) {
  31048. defines.ALPHAFROMALBEDO = true;
  31049. }
  31050. }
  31051. if (this._useSpecularOverAlpha) {
  31052. defines.SPECULAROVERALPHA = true;
  31053. }
  31054. if (this._usePhysicalLightFalloff) {
  31055. defines.USEPHYSICALLIGHTFALLOFF = true;
  31056. }
  31057. if (this._useRadianceOverAlpha) {
  31058. defines.RADIANCEOVERALPHA = true;
  31059. }
  31060. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  31061. defines.METALLICWORKFLOW = true;
  31062. }
  31063. if (!this.backFaceCulling && this._twoSidedLighting) {
  31064. defines.TWOSIDEDLIGHTING = true;
  31065. }
  31066. defines.ALPHATESTVALUE = this._alphaCutOff;
  31067. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  31068. defines.ALPHABLEND = this.needAlphaBlending();
  31069. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  31070. }
  31071. if (defines._areImageProcessingDirty) {
  31072. if (!this._imageProcessingConfiguration.isReady()) {
  31073. return false;
  31074. }
  31075. this._imageProcessingConfiguration.prepareDefines(defines);
  31076. }
  31077. // Misc.
  31078. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  31079. // Values that need to be evaluated on every frame
  31080. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  31081. // Attribs
  31082. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  31083. if (mesh) {
  31084. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31085. mesh.createNormals(true);
  31086. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  31087. }
  31088. }
  31089. }
  31090. // Get correct effect
  31091. if (defines.isDirty) {
  31092. defines.markAsProcessed();
  31093. scene.resetCachedMaterial();
  31094. // Fallbacks
  31095. var fallbacks = new BABYLON.EffectFallbacks();
  31096. if (defines.ENVIRONMENTBRDF) {
  31097. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  31098. }
  31099. if (defines.REFLECTION) {
  31100. fallbacks.addFallback(0, "REFLECTION");
  31101. }
  31102. if (defines.REFRACTION) {
  31103. fallbacks.addFallback(0, "REFRACTION");
  31104. }
  31105. if (defines.REFLECTIVITY) {
  31106. fallbacks.addFallback(0, "REFLECTIVITY");
  31107. }
  31108. if (defines.BUMP) {
  31109. fallbacks.addFallback(0, "BUMP");
  31110. }
  31111. if (defines.PARALLAX) {
  31112. fallbacks.addFallback(1, "PARALLAX");
  31113. }
  31114. if (defines.PARALLAXOCCLUSION) {
  31115. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31116. }
  31117. if (defines.SPECULAROVERALPHA) {
  31118. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31119. }
  31120. if (defines.FOG) {
  31121. fallbacks.addFallback(1, "FOG");
  31122. }
  31123. if (defines.POINTSIZE) {
  31124. fallbacks.addFallback(0, "POINTSIZE");
  31125. }
  31126. if (defines.LOGARITHMICDEPTH) {
  31127. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31128. }
  31129. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31130. if (defines.SPECULARTERM) {
  31131. fallbacks.addFallback(0, "SPECULARTERM");
  31132. }
  31133. if (defines.NUM_BONE_INFLUENCERS > 0) {
  31134. fallbacks.addCPUSkinningFallback(0, mesh);
  31135. }
  31136. //Attributes
  31137. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31138. if (defines.NORMAL) {
  31139. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31140. }
  31141. if (defines.TANGENT) {
  31142. attribs.push(BABYLON.VertexBuffer.TangentKind);
  31143. }
  31144. if (defines.UV1) {
  31145. attribs.push(BABYLON.VertexBuffer.UVKind);
  31146. }
  31147. if (defines.UV2) {
  31148. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31149. }
  31150. if (defines.VERTEXCOLOR) {
  31151. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31152. }
  31153. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31154. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31155. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  31156. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  31157. "vFogInfos", "vFogColor", "pointSize",
  31158. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31159. "mBones",
  31160. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31161. "vLightingIntensity",
  31162. "logarithmicDepthConstant",
  31163. "vSphericalX", "vSphericalY", "vSphericalZ",
  31164. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  31165. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  31166. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos"
  31167. ];
  31168. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  31169. "bumpSampler", "lightmapSampler", "opacitySampler",
  31170. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  31171. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  31172. "microSurfaceSampler", "environmentBrdfSampler"];
  31173. var uniformBuffers = ["Material", "Scene"];
  31174. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  31175. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  31176. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  31177. uniformsNames: uniforms,
  31178. uniformBuffersNames: uniformBuffers,
  31179. samplers: samplers,
  31180. defines: defines,
  31181. maxSimultaneousLights: this._maxSimultaneousLights
  31182. });
  31183. var onCompiled = function (effect) {
  31184. if (this.onCompiled) {
  31185. this.onCompiled(effect);
  31186. }
  31187. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  31188. }.bind(this);
  31189. var join = defines.toString();
  31190. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  31191. attributes: attribs,
  31192. uniformsNames: uniforms,
  31193. uniformBuffersNames: uniformBuffers,
  31194. samplers: samplers,
  31195. defines: join,
  31196. fallbacks: fallbacks,
  31197. onCompiled: onCompiled,
  31198. onError: this.onError,
  31199. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31200. }, engine), defines);
  31201. this.buildUniformLayout();
  31202. }
  31203. if (!subMesh.effect.isReady()) {
  31204. return false;
  31205. }
  31206. defines._renderId = scene.getRenderId();
  31207. this._wasPreviouslyReady = true;
  31208. return true;
  31209. };
  31210. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  31211. // Order is important !
  31212. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  31213. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  31214. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31215. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31216. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31217. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  31218. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  31219. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31220. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31221. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31222. this._uniformBuffer.addUniform("albedoMatrix", 16);
  31223. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31224. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31225. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31226. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31227. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  31228. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  31229. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31230. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31231. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31232. this._uniformBuffer.addUniform("vReflectionColor", 3);
  31233. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  31234. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  31235. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  31236. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  31237. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  31238. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31239. this._uniformBuffer.addUniform("pointSize", 1);
  31240. this._uniformBuffer.create();
  31241. };
  31242. PBRBaseMaterial.prototype.unbind = function () {
  31243. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31244. this._uniformBuffer.setTexture("reflectionSampler", null);
  31245. }
  31246. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31247. this._uniformBuffer.setTexture("refractionSampler", null);
  31248. }
  31249. _super.prototype.unbind.call(this);
  31250. };
  31251. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  31252. this._activeEffect.setMatrix("world", world);
  31253. };
  31254. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31255. var scene = this.getScene();
  31256. var defines = subMesh._materialDefines;
  31257. if (!defines) {
  31258. return;
  31259. }
  31260. var effect = subMesh.effect;
  31261. this._activeEffect = effect;
  31262. // Matrices
  31263. this.bindOnlyWorldMatrix(world);
  31264. // Bones
  31265. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  31266. if (this._mustRebind(scene, effect, mesh.visibility)) {
  31267. this._uniformBuffer.bindToEffect(effect, "Material");
  31268. this.bindViewProjection(effect);
  31269. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31270. // Texture uniforms
  31271. if (scene.texturesEnabled) {
  31272. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31273. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  31274. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  31275. }
  31276. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31277. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  31278. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31279. }
  31280. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31281. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31282. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31283. }
  31284. var reflectionTexture = this._getReflectionTexture();
  31285. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31286. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  31287. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  31288. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  31289. var polynomials = reflectionTexture.sphericalPolynomial;
  31290. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  31291. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  31292. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  31293. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  31294. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  31295. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  31296. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  31297. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  31298. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  31299. }
  31300. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  31301. }
  31302. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31303. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31304. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31305. }
  31306. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31307. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31308. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31309. }
  31310. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31311. if (this._metallicTexture) {
  31312. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  31313. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  31314. }
  31315. else if (this._reflectivityTexture) {
  31316. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  31317. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  31318. }
  31319. if (this._microSurfaceTexture) {
  31320. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  31321. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  31322. }
  31323. }
  31324. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31325. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  31326. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31327. }
  31328. var refractionTexture = this._getRefractionTexture();
  31329. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31330. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  31331. var depth = 1.0;
  31332. if (!refractionTexture.isCube) {
  31333. if (refractionTexture.depth) {
  31334. depth = refractionTexture.depth;
  31335. }
  31336. }
  31337. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  31338. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  31339. }
  31340. }
  31341. // Point size
  31342. if (this.pointsCloud) {
  31343. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31344. }
  31345. // Colors
  31346. if (defines.METALLICWORKFLOW) {
  31347. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  31348. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  31349. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  31350. }
  31351. else {
  31352. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  31353. }
  31354. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  31355. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  31356. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  31357. // Misc
  31358. this._lightingInfos.x = this._directIntensity;
  31359. this._lightingInfos.y = this._emissiveIntensity;
  31360. this._lightingInfos.z = this._environmentIntensity;
  31361. this._lightingInfos.w = this._specularIntensity;
  31362. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  31363. }
  31364. // Textures
  31365. if (scene.texturesEnabled) {
  31366. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31367. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  31368. }
  31369. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31370. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  31371. }
  31372. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31373. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  31374. }
  31375. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31376. if (defines.LODBASEDMICROSFURACE) {
  31377. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  31378. }
  31379. else {
  31380. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  31381. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  31382. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  31383. }
  31384. }
  31385. if (defines.ENVIRONMENTBRDF) {
  31386. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  31387. }
  31388. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31389. if (defines.LODBASEDMICROSFURACE) {
  31390. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  31391. }
  31392. else {
  31393. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  31394. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  31395. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  31396. }
  31397. }
  31398. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31399. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  31400. }
  31401. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31402. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  31403. }
  31404. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31405. if (this._metallicTexture) {
  31406. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  31407. }
  31408. else if (this._reflectivityTexture) {
  31409. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  31410. }
  31411. if (this._microSurfaceTexture) {
  31412. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  31413. }
  31414. }
  31415. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31416. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  31417. }
  31418. }
  31419. // Clip plane
  31420. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  31421. // Colors
  31422. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  31423. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  31424. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31425. }
  31426. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  31427. // Lights
  31428. if (scene.lightsEnabled && !this._disableLighting) {
  31429. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  31430. }
  31431. // View
  31432. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  31433. this.bindView(effect);
  31434. }
  31435. // Fog
  31436. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  31437. // Morph targets
  31438. if (defines.NUM_MORPH_INFLUENCERS) {
  31439. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  31440. }
  31441. // image processing
  31442. this._imageProcessingConfiguration.bind(this._activeEffect);
  31443. // Log. depth
  31444. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  31445. }
  31446. this._uniformBuffer.update();
  31447. this._afterBind(mesh);
  31448. scene = null;
  31449. };
  31450. PBRBaseMaterial.prototype.getAnimatables = function () {
  31451. var results = [];
  31452. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  31453. results.push(this._albedoTexture);
  31454. }
  31455. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31456. results.push(this._ambientTexture);
  31457. }
  31458. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31459. results.push(this._opacityTexture);
  31460. }
  31461. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31462. results.push(this._reflectionTexture);
  31463. }
  31464. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31465. results.push(this._emissiveTexture);
  31466. }
  31467. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  31468. results.push(this._metallicTexture);
  31469. }
  31470. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  31471. results.push(this._reflectivityTexture);
  31472. }
  31473. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31474. results.push(this._bumpTexture);
  31475. }
  31476. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31477. results.push(this._lightmapTexture);
  31478. }
  31479. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31480. results.push(this._refractionTexture);
  31481. }
  31482. return results;
  31483. };
  31484. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  31485. if (this._reflectionTexture) {
  31486. return this._reflectionTexture;
  31487. }
  31488. return this.getScene().environmentTexture;
  31489. };
  31490. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  31491. if (this._refractionTexture) {
  31492. return this._refractionTexture;
  31493. }
  31494. if (this._linkRefractionWithTransparency) {
  31495. return this.getScene().environmentTexture;
  31496. }
  31497. return null;
  31498. };
  31499. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31500. if (forceDisposeTextures) {
  31501. if (this._albedoTexture) {
  31502. this._albedoTexture.dispose();
  31503. }
  31504. if (this._ambientTexture) {
  31505. this._ambientTexture.dispose();
  31506. }
  31507. if (this._opacityTexture) {
  31508. this._opacityTexture.dispose();
  31509. }
  31510. if (this._reflectionTexture) {
  31511. this._reflectionTexture.dispose();
  31512. }
  31513. if (this._environmentBRDFTexture) {
  31514. this._environmentBRDFTexture.dispose();
  31515. }
  31516. if (this._emissiveTexture) {
  31517. this._emissiveTexture.dispose();
  31518. }
  31519. if (this._metallicTexture) {
  31520. this._metallicTexture.dispose();
  31521. }
  31522. if (this._reflectivityTexture) {
  31523. this._reflectivityTexture.dispose();
  31524. }
  31525. if (this._bumpTexture) {
  31526. this._bumpTexture.dispose();
  31527. }
  31528. if (this._lightmapTexture) {
  31529. this._lightmapTexture.dispose();
  31530. }
  31531. if (this._refractionTexture) {
  31532. this._refractionTexture.dispose();
  31533. }
  31534. }
  31535. this._renderTargets.dispose();
  31536. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31537. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31538. }
  31539. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31540. };
  31541. return PBRBaseMaterial;
  31542. }(BABYLON.PushMaterial));
  31543. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  31544. __decorate([
  31545. BABYLON.serializeAsImageProcessingConfiguration()
  31546. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  31547. __decorate([
  31548. BABYLON.serialize()
  31549. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  31550. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  31551. })(BABYLON || (BABYLON = {}));
  31552. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  31553. var BABYLON;
  31554. (function (BABYLON) {
  31555. var Internals;
  31556. (function (Internals) {
  31557. /**
  31558. * The Physically based simple base material of BJS.
  31559. *
  31560. * This enables better naming and convention enforcements on top of the pbrMaterial.
  31561. * It is used as the base class for both the specGloss and metalRough conventions.
  31562. */
  31563. var PBRBaseSimpleMaterial = (function (_super) {
  31564. __extends(PBRBaseSimpleMaterial, _super);
  31565. /**
  31566. * Instantiates a new PBRMaterial instance.
  31567. *
  31568. * @param name The material name
  31569. * @param scene The scene the material will be use in.
  31570. */
  31571. function PBRBaseSimpleMaterial(name, scene) {
  31572. var _this = _super.call(this, name, scene) || this;
  31573. /**
  31574. * Number of Simultaneous lights allowed on the material.
  31575. */
  31576. _this.maxSimultaneousLights = 4;
  31577. /**
  31578. * If sets to true, disables all the lights affecting the material.
  31579. */
  31580. _this.disableLighting = false;
  31581. /**
  31582. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  31583. */
  31584. _this.invertNormalMapX = false;
  31585. /**
  31586. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  31587. */
  31588. _this.invertNormalMapY = false;
  31589. /**
  31590. * Emissivie color used to self-illuminate the model.
  31591. */
  31592. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  31593. /**
  31594. * Occlusion Channel Strenght.
  31595. */
  31596. _this.occlusionStrength = 1.0;
  31597. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  31598. _this._useAmbientInGrayScale = true;
  31599. return _this;
  31600. }
  31601. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  31602. /**
  31603. * Gets the current transparency mode.
  31604. */
  31605. get: function () {
  31606. return this._transparencyMode;
  31607. },
  31608. /**
  31609. * Sets the transparency mode of the material.
  31610. */
  31611. set: function (value) {
  31612. if (this._transparencyMode === value) {
  31613. return;
  31614. }
  31615. this._transparencyMode = value;
  31616. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  31617. this._forceAlphaTest = true;
  31618. }
  31619. else {
  31620. this._forceAlphaTest = false;
  31621. }
  31622. this._markAllSubMeshesAsTexturesDirty();
  31623. },
  31624. enumerable: true,
  31625. configurable: true
  31626. });
  31627. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  31628. /**
  31629. * Gets the current double sided mode.
  31630. */
  31631. get: function () {
  31632. return this._twoSidedLighting;
  31633. },
  31634. /**
  31635. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31636. */
  31637. set: function (value) {
  31638. if (this._twoSidedLighting === value) {
  31639. return;
  31640. }
  31641. this._twoSidedLighting = value;
  31642. this.backFaceCulling = !value;
  31643. this._markAllSubMeshesAsTexturesDirty();
  31644. },
  31645. enumerable: true,
  31646. configurable: true
  31647. });
  31648. /**
  31649. * Specifies wether or not the alpha value of the albedo texture should be used.
  31650. */
  31651. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  31652. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  31653. };
  31654. /**
  31655. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  31656. */
  31657. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  31658. if (this._linkRefractionWithTransparency) {
  31659. return false;
  31660. }
  31661. return (this.alpha < 1.0) ||
  31662. (this._shouldUseAlphaFromAlbedoTexture() &&
  31663. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  31664. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  31665. };
  31666. /**
  31667. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  31668. */
  31669. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  31670. if (this._linkRefractionWithTransparency) {
  31671. return false;
  31672. }
  31673. return this._shouldUseAlphaFromAlbedoTexture() &&
  31674. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  31675. };
  31676. /**
  31677. * Return the active textures of the material.
  31678. */
  31679. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  31680. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31681. if (this.environmentTexture) {
  31682. activeTextures.push(this.environmentTexture);
  31683. }
  31684. if (this.normalTexture) {
  31685. activeTextures.push(this.normalTexture);
  31686. }
  31687. if (this.emissiveTexture) {
  31688. activeTextures.push(this.emissiveTexture);
  31689. }
  31690. if (this.occlusionTexture) {
  31691. activeTextures.push(this.occlusionTexture);
  31692. }
  31693. return activeTextures;
  31694. };
  31695. return PBRBaseSimpleMaterial;
  31696. }(BABYLON.PBRBaseMaterial));
  31697. __decorate([
  31698. BABYLON.serialize(),
  31699. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31700. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  31701. __decorate([
  31702. BABYLON.serialize(),
  31703. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31704. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  31705. __decorate([
  31706. BABYLON.serializeAsTexture(),
  31707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  31708. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  31709. __decorate([
  31710. BABYLON.serialize(),
  31711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31712. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  31713. __decorate([
  31714. BABYLON.serialize(),
  31715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31716. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  31717. __decorate([
  31718. BABYLON.serializeAsTexture(),
  31719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  31720. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  31721. __decorate([
  31722. BABYLON.serializeAsColor3("emissive"),
  31723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31724. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  31725. __decorate([
  31726. BABYLON.serializeAsTexture(),
  31727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31728. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  31729. __decorate([
  31730. BABYLON.serialize(),
  31731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  31732. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  31733. __decorate([
  31734. BABYLON.serializeAsTexture(),
  31735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  31736. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  31737. __decorate([
  31738. BABYLON.serialize(),
  31739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  31740. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  31741. __decorate([
  31742. BABYLON.serialize()
  31743. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  31744. __decorate([
  31745. BABYLON.serialize()
  31746. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  31747. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  31748. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31749. })(BABYLON || (BABYLON = {}));
  31750. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  31751. var BABYLON;
  31752. (function (BABYLON) {
  31753. /**
  31754. * The Physically based material of BJS.
  31755. *
  31756. * This offers the main features of a standard PBR material.
  31757. * For more information, please refer to the documentation :
  31758. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31759. */
  31760. var PBRMaterial = (function (_super) {
  31761. __extends(PBRMaterial, _super);
  31762. /**
  31763. * Instantiates a new PBRMaterial instance.
  31764. *
  31765. * @param name The material name
  31766. * @param scene The scene the material will be use in.
  31767. */
  31768. function PBRMaterial(name, scene) {
  31769. var _this = _super.call(this, name, scene) || this;
  31770. /**
  31771. * Intensity of the direct lights e.g. the four lights available in your scene.
  31772. * This impacts both the direct diffuse and specular highlights.
  31773. */
  31774. _this.directIntensity = 1.0;
  31775. /**
  31776. * Intensity of the emissive part of the material.
  31777. * This helps controlling the emissive effect without modifying the emissive color.
  31778. */
  31779. _this.emissiveIntensity = 1.0;
  31780. /**
  31781. * Intensity of the environment e.g. how much the environment will light the object
  31782. * either through harmonics for rough material or through the refelction for shiny ones.
  31783. */
  31784. _this.environmentIntensity = 1.0;
  31785. /**
  31786. * This is a special control allowing the reduction of the specular highlights coming from the
  31787. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31788. */
  31789. _this.specularIntensity = 1.0;
  31790. /**
  31791. * Debug Control allowing disabling the bump map on this material.
  31792. */
  31793. _this.disableBumpMap = false;
  31794. /**
  31795. * AKA Occlusion Texture Intensity in other nomenclature.
  31796. */
  31797. _this.ambientTextureStrength = 1.0;
  31798. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  31799. /**
  31800. * AKA Diffuse Color in other nomenclature.
  31801. */
  31802. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  31803. /**
  31804. * AKA Specular Color in other nomenclature.
  31805. */
  31806. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31807. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  31808. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  31809. /**
  31810. * AKA Glossiness in other nomenclature.
  31811. */
  31812. _this.microSurface = 1.0;
  31813. /**
  31814. * source material index of refraction (IOR)' / 'destination material IOR.
  31815. */
  31816. _this.indexOfRefraction = 0.66;
  31817. /**
  31818. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31819. */
  31820. _this.invertRefractionY = false;
  31821. /**
  31822. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31823. * Materials half opaque for instance using refraction could benefit from this control.
  31824. */
  31825. _this.linkRefractionWithTransparency = false;
  31826. _this.useLightmapAsShadowmap = false;
  31827. /**
  31828. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31829. */
  31830. _this.useAlphaFromAlbedoTexture = false;
  31831. /**
  31832. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31833. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31834. */
  31835. _this.useSpecularOverAlpha = true;
  31836. /**
  31837. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31838. */
  31839. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  31840. /**
  31841. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31842. */
  31843. _this.useRoughnessFromMetallicTextureAlpha = true;
  31844. /**
  31845. * Specifies if the metallic texture contains the roughness information in its green channel.
  31846. */
  31847. _this.useRoughnessFromMetallicTextureGreen = false;
  31848. /**
  31849. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31850. */
  31851. _this.useMetallnessFromMetallicTextureBlue = false;
  31852. /**
  31853. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31854. */
  31855. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  31856. /**
  31857. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31858. */
  31859. _this.useAmbientInGrayScale = false;
  31860. /**
  31861. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31862. * The material will try to infer what glossiness each pixel should be.
  31863. */
  31864. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  31865. /**
  31866. * BJS is using an harcoded light falloff based on a manually sets up range.
  31867. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  31868. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  31869. */
  31870. _this.usePhysicalLightFalloff = true;
  31871. /**
  31872. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  31873. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  31874. */
  31875. _this.useRadianceOverAlpha = true;
  31876. /**
  31877. * Allows using the bump map in parallax mode.
  31878. */
  31879. _this.useParallax = false;
  31880. /**
  31881. * Allows using the bump map in parallax occlusion mode.
  31882. */
  31883. _this.useParallaxOcclusion = false;
  31884. /**
  31885. * Controls the scale bias of the parallax mode.
  31886. */
  31887. _this.parallaxScaleBias = 0.05;
  31888. /**
  31889. * If sets to true, disables all the lights affecting the material.
  31890. */
  31891. _this.disableLighting = false;
  31892. /**
  31893. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  31894. */
  31895. _this.forceIrradianceInFragment = false;
  31896. /**
  31897. * Number of Simultaneous lights allowed on the material.
  31898. */
  31899. _this.maxSimultaneousLights = 4;
  31900. /**
  31901. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  31902. */
  31903. _this.invertNormalMapX = false;
  31904. /**
  31905. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  31906. */
  31907. _this.invertNormalMapY = false;
  31908. /**
  31909. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31910. */
  31911. _this.twoSidedLighting = false;
  31912. /**
  31913. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  31914. * in your scene composition.
  31915. */
  31916. _this.preMultiplyAlpha = false;
  31917. /**
  31918. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31919. * And/Or occlude the blended part.
  31920. */
  31921. _this.useAlphaFresnel = false;
  31922. /**
  31923. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31924. * And/Or occlude the blended part.
  31925. */
  31926. _this.environmentBRDFTexture = null;
  31927. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  31928. return _this;
  31929. }
  31930. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  31931. /**
  31932. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  31933. */
  31934. get: function () {
  31935. return this._PBRMATERIAL_OPAQUE;
  31936. },
  31937. enumerable: true,
  31938. configurable: true
  31939. });
  31940. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  31941. /**
  31942. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  31943. */
  31944. get: function () {
  31945. return this._PBRMATERIAL_ALPHATEST;
  31946. },
  31947. enumerable: true,
  31948. configurable: true
  31949. });
  31950. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  31951. /**
  31952. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  31953. */
  31954. get: function () {
  31955. return this._PBRMATERIAL_ALPHABLEND;
  31956. },
  31957. enumerable: true,
  31958. configurable: true
  31959. });
  31960. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  31961. /**
  31962. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  31963. * They are also discarded below the alpha cutoff threshold to improve performances.
  31964. */
  31965. get: function () {
  31966. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  31967. },
  31968. enumerable: true,
  31969. configurable: true
  31970. });
  31971. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  31972. /**
  31973. * Gets the image processing configuration used either in this material.
  31974. */
  31975. get: function () {
  31976. return this._imageProcessingConfiguration;
  31977. },
  31978. /**
  31979. * Sets the Default image processing configuration used either in the this material.
  31980. *
  31981. * If sets to null, the scene one is in use.
  31982. */
  31983. set: function (value) {
  31984. this._attachImageProcessingConfiguration(value);
  31985. // Ensure the effect will be rebuilt.
  31986. this._markAllSubMeshesAsTexturesDirty();
  31987. },
  31988. enumerable: true,
  31989. configurable: true
  31990. });
  31991. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  31992. /**
  31993. * Gets wether the color curves effect is enabled.
  31994. */
  31995. get: function () {
  31996. return this.imageProcessingConfiguration.colorCurvesEnabled;
  31997. },
  31998. /**
  31999. * Sets wether the color curves effect is enabled.
  32000. */
  32001. set: function (value) {
  32002. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  32003. },
  32004. enumerable: true,
  32005. configurable: true
  32006. });
  32007. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  32008. /**
  32009. * Gets wether the color grading effect is enabled.
  32010. */
  32011. get: function () {
  32012. return this.imageProcessingConfiguration.colorGradingEnabled;
  32013. },
  32014. /**
  32015. * Gets wether the color grading effect is enabled.
  32016. */
  32017. set: function (value) {
  32018. this.imageProcessingConfiguration.colorGradingEnabled = value;
  32019. },
  32020. enumerable: true,
  32021. configurable: true
  32022. });
  32023. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  32024. /**
  32025. * Gets wether tonemapping is enabled or not.
  32026. */
  32027. get: function () {
  32028. return this._imageProcessingConfiguration.toneMappingEnabled;
  32029. },
  32030. /**
  32031. * Sets wether tonemapping is enabled or not
  32032. */
  32033. set: function (value) {
  32034. this._imageProcessingConfiguration.toneMappingEnabled = value;
  32035. },
  32036. enumerable: true,
  32037. configurable: true
  32038. });
  32039. ;
  32040. ;
  32041. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  32042. /**
  32043. * The camera exposure used on this material.
  32044. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32045. * This corresponds to a photographic exposure.
  32046. */
  32047. get: function () {
  32048. return this._imageProcessingConfiguration.exposure;
  32049. },
  32050. /**
  32051. * The camera exposure used on this material.
  32052. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32053. * This corresponds to a photographic exposure.
  32054. */
  32055. set: function (value) {
  32056. this._imageProcessingConfiguration.exposure = value;
  32057. },
  32058. enumerable: true,
  32059. configurable: true
  32060. });
  32061. ;
  32062. ;
  32063. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  32064. /**
  32065. * Gets The camera contrast used on this material.
  32066. */
  32067. get: function () {
  32068. return this._imageProcessingConfiguration.contrast;
  32069. },
  32070. /**
  32071. * Sets The camera contrast used on this material.
  32072. */
  32073. set: function (value) {
  32074. this._imageProcessingConfiguration.contrast = value;
  32075. },
  32076. enumerable: true,
  32077. configurable: true
  32078. });
  32079. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  32080. /**
  32081. * Gets the Color Grading 2D Lookup Texture.
  32082. */
  32083. get: function () {
  32084. return this._imageProcessingConfiguration.colorGradingTexture;
  32085. },
  32086. /**
  32087. * Sets the Color Grading 2D Lookup Texture.
  32088. */
  32089. set: function (value) {
  32090. this._imageProcessingConfiguration.colorGradingTexture = value;
  32091. },
  32092. enumerable: true,
  32093. configurable: true
  32094. });
  32095. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  32096. /**
  32097. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32098. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32099. * 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;
  32100. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32101. */
  32102. get: function () {
  32103. return this._imageProcessingConfiguration.colorCurves;
  32104. },
  32105. /**
  32106. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32107. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32108. * 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;
  32109. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32110. */
  32111. set: function (value) {
  32112. this._imageProcessingConfiguration.colorCurves = value;
  32113. },
  32114. enumerable: true,
  32115. configurable: true
  32116. });
  32117. PBRMaterial.prototype.getClassName = function () {
  32118. return "PBRMaterial";
  32119. };
  32120. PBRMaterial.prototype.getActiveTextures = function () {
  32121. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32122. if (this._albedoTexture) {
  32123. activeTextures.push(this._albedoTexture);
  32124. }
  32125. if (this._ambientTexture) {
  32126. activeTextures.push(this._ambientTexture);
  32127. }
  32128. if (this._opacityTexture) {
  32129. activeTextures.push(this._opacityTexture);
  32130. }
  32131. if (this._reflectionTexture) {
  32132. activeTextures.push(this._reflectionTexture);
  32133. }
  32134. if (this._emissiveTexture) {
  32135. activeTextures.push(this._emissiveTexture);
  32136. }
  32137. if (this._reflectionTexture) {
  32138. activeTextures.push(this._reflectionTexture);
  32139. }
  32140. if (this._metallicTexture) {
  32141. activeTextures.push(this._metallicTexture);
  32142. }
  32143. if (this._microSurfaceTexture) {
  32144. activeTextures.push(this._microSurfaceTexture);
  32145. }
  32146. if (this._bumpTexture) {
  32147. activeTextures.push(this._bumpTexture);
  32148. }
  32149. if (this._lightmapTexture) {
  32150. activeTextures.push(this._lightmapTexture);
  32151. }
  32152. if (this._refractionTexture) {
  32153. activeTextures.push(this._refractionTexture);
  32154. }
  32155. return activeTextures;
  32156. };
  32157. PBRMaterial.prototype.hasTexture = function (texture) {
  32158. if (_super.prototype.hasTexture.call(this, texture)) {
  32159. return true;
  32160. }
  32161. if (this._albedoTexture === texture) {
  32162. return true;
  32163. }
  32164. if (this._ambientTexture === texture) {
  32165. return true;
  32166. }
  32167. if (this._opacityTexture === texture) {
  32168. return true;
  32169. }
  32170. if (this._reflectionTexture === texture) {
  32171. return true;
  32172. }
  32173. if (this._metallicTexture === texture) {
  32174. return true;
  32175. }
  32176. if (this._microSurfaceTexture === texture) {
  32177. return true;
  32178. }
  32179. if (this._bumpTexture === texture) {
  32180. return true;
  32181. }
  32182. if (this._lightmapTexture === texture) {
  32183. return true;
  32184. }
  32185. if (this._refractionTexture === texture) {
  32186. return true;
  32187. }
  32188. return false;
  32189. };
  32190. PBRMaterial.prototype.clone = function (name) {
  32191. var _this = this;
  32192. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  32193. };
  32194. PBRMaterial.prototype.serialize = function () {
  32195. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32196. serializationObject.customType = "BABYLON.PBRMaterial";
  32197. return serializationObject;
  32198. };
  32199. // Statics
  32200. PBRMaterial.Parse = function (source, scene, rootUrl) {
  32201. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  32202. };
  32203. return PBRMaterial;
  32204. }(BABYLON.PBRBaseMaterial));
  32205. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  32206. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  32207. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  32208. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  32209. __decorate([
  32210. BABYLON.serialize(),
  32211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32212. ], PBRMaterial.prototype, "directIntensity", void 0);
  32213. __decorate([
  32214. BABYLON.serialize(),
  32215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32216. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  32217. __decorate([
  32218. BABYLON.serialize(),
  32219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32220. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  32221. __decorate([
  32222. BABYLON.serialize(),
  32223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32224. ], PBRMaterial.prototype, "specularIntensity", void 0);
  32225. __decorate([
  32226. BABYLON.serialize(),
  32227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32228. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  32229. __decorate([
  32230. BABYLON.serializeAsTexture(),
  32231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32232. ], PBRMaterial.prototype, "albedoTexture", void 0);
  32233. __decorate([
  32234. BABYLON.serializeAsTexture(),
  32235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32236. ], PBRMaterial.prototype, "ambientTexture", void 0);
  32237. __decorate([
  32238. BABYLON.serialize(),
  32239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32240. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  32241. __decorate([
  32242. BABYLON.serializeAsTexture(),
  32243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32244. ], PBRMaterial.prototype, "opacityTexture", void 0);
  32245. __decorate([
  32246. BABYLON.serializeAsTexture(),
  32247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32248. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  32249. __decorate([
  32250. BABYLON.serializeAsTexture(),
  32251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32252. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  32253. __decorate([
  32254. BABYLON.serializeAsTexture(),
  32255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32256. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  32257. __decorate([
  32258. BABYLON.serializeAsTexture(),
  32259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32260. ], PBRMaterial.prototype, "metallicTexture", void 0);
  32261. __decorate([
  32262. BABYLON.serialize(),
  32263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32264. ], PBRMaterial.prototype, "metallic", void 0);
  32265. __decorate([
  32266. BABYLON.serialize(),
  32267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32268. ], PBRMaterial.prototype, "roughness", void 0);
  32269. __decorate([
  32270. BABYLON.serializeAsTexture(),
  32271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32272. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  32273. __decorate([
  32274. BABYLON.serializeAsTexture(),
  32275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32276. ], PBRMaterial.prototype, "bumpTexture", void 0);
  32277. __decorate([
  32278. BABYLON.serializeAsTexture(),
  32279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  32280. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  32281. __decorate([
  32282. BABYLON.serializeAsTexture(),
  32283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32284. ], PBRMaterial.prototype, "refractionTexture", void 0);
  32285. __decorate([
  32286. BABYLON.serializeAsColor3("ambient"),
  32287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32288. ], PBRMaterial.prototype, "ambientColor", void 0);
  32289. __decorate([
  32290. BABYLON.serializeAsColor3("albedo"),
  32291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32292. ], PBRMaterial.prototype, "albedoColor", void 0);
  32293. __decorate([
  32294. BABYLON.serializeAsColor3("reflectivity"),
  32295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32296. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  32297. __decorate([
  32298. BABYLON.serializeAsColor3("reflection"),
  32299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32300. ], PBRMaterial.prototype, "reflectionColor", void 0);
  32301. __decorate([
  32302. BABYLON.serializeAsColor3("emissive"),
  32303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32304. ], PBRMaterial.prototype, "emissiveColor", void 0);
  32305. __decorate([
  32306. BABYLON.serialize(),
  32307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32308. ], PBRMaterial.prototype, "microSurface", void 0);
  32309. __decorate([
  32310. BABYLON.serialize(),
  32311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32312. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  32313. __decorate([
  32314. BABYLON.serialize(),
  32315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32316. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  32317. __decorate([
  32318. BABYLON.serialize(),
  32319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32320. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  32321. __decorate([
  32322. BABYLON.serialize(),
  32323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32324. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  32325. __decorate([
  32326. BABYLON.serialize(),
  32327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32328. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  32329. __decorate([
  32330. BABYLON.serialize(),
  32331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32332. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  32333. __decorate([
  32334. BABYLON.serialize(),
  32335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32336. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  32337. __decorate([
  32338. BABYLON.serialize(),
  32339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32340. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  32341. __decorate([
  32342. BABYLON.serialize(),
  32343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32344. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  32345. __decorate([
  32346. BABYLON.serialize(),
  32347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32348. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  32349. __decorate([
  32350. BABYLON.serialize(),
  32351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32352. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  32353. __decorate([
  32354. BABYLON.serialize(),
  32355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32356. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  32357. __decorate([
  32358. BABYLON.serialize(),
  32359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32360. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  32361. __decorate([
  32362. BABYLON.serialize(),
  32363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32364. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  32365. __decorate([
  32366. BABYLON.serialize(),
  32367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32368. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  32369. __decorate([
  32370. BABYLON.serialize(),
  32371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32372. ], PBRMaterial.prototype, "useParallax", void 0);
  32373. __decorate([
  32374. BABYLON.serialize(),
  32375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32376. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  32377. __decorate([
  32378. BABYLON.serialize(),
  32379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32380. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  32381. __decorate([
  32382. BABYLON.serialize(),
  32383. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32384. ], PBRMaterial.prototype, "disableLighting", void 0);
  32385. __decorate([
  32386. BABYLON.serialize(),
  32387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32388. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  32389. __decorate([
  32390. BABYLON.serialize(),
  32391. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32392. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  32393. __decorate([
  32394. BABYLON.serialize(),
  32395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32396. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  32397. __decorate([
  32398. BABYLON.serialize(),
  32399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32400. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  32401. __decorate([
  32402. BABYLON.serialize(),
  32403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32404. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  32405. __decorate([
  32406. BABYLON.serialize(),
  32407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32408. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  32409. __decorate([
  32410. BABYLON.serialize(),
  32411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32412. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  32413. __decorate([
  32414. BABYLON.serializeAsTexture(),
  32415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32416. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  32417. BABYLON.PBRMaterial = PBRMaterial;
  32418. })(BABYLON || (BABYLON = {}));
  32419. //# sourceMappingURL=babylon.pbrMaterial.js.map
  32420. var BABYLON;
  32421. (function (BABYLON) {
  32422. /**
  32423. * The PBR material of BJS following the metal roughness convention.
  32424. *
  32425. * This fits to the PBR convention in the GLTF definition:
  32426. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  32427. */
  32428. var PBRMetallicRoughnessMaterial = (function (_super) {
  32429. __extends(PBRMetallicRoughnessMaterial, _super);
  32430. /**
  32431. * Instantiates a new PBRMetalRoughnessMaterial instance.
  32432. *
  32433. * @param name The material name
  32434. * @param scene The scene the material will be use in.
  32435. */
  32436. function PBRMetallicRoughnessMaterial(name, scene) {
  32437. var _this = _super.call(this, name, scene) || this;
  32438. _this._useRoughnessFromMetallicTextureAlpha = false;
  32439. _this._useRoughnessFromMetallicTextureGreen = true;
  32440. _this._useMetallnessFromMetallicTextureBlue = true;
  32441. return _this;
  32442. }
  32443. /**
  32444. * Return the currrent class name of the material.
  32445. */
  32446. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  32447. return "PBRMetallicRoughnessMaterial";
  32448. };
  32449. /**
  32450. * Return the active textures of the material.
  32451. */
  32452. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  32453. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32454. if (this.baseTexture) {
  32455. activeTextures.push(this.baseTexture);
  32456. }
  32457. if (this.metallicRoughnessTexture) {
  32458. activeTextures.push(this.metallicRoughnessTexture);
  32459. }
  32460. return activeTextures;
  32461. };
  32462. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  32463. if (_super.prototype.hasTexture.call(this, texture)) {
  32464. return true;
  32465. }
  32466. if (this.baseTexture === texture) {
  32467. return true;
  32468. }
  32469. if (this.metallicRoughnessTexture === texture) {
  32470. return true;
  32471. }
  32472. return false;
  32473. };
  32474. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  32475. var _this = this;
  32476. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  32477. };
  32478. /**
  32479. * Serialize the material to a parsable JSON object.
  32480. */
  32481. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  32482. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32483. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  32484. return serializationObject;
  32485. };
  32486. /**
  32487. * Parses a JSON object correponding to the serialize function.
  32488. */
  32489. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  32490. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  32491. };
  32492. return PBRMetallicRoughnessMaterial;
  32493. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  32494. __decorate([
  32495. BABYLON.serializeAsColor3(),
  32496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  32497. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  32498. __decorate([
  32499. BABYLON.serializeAsTexture(),
  32500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  32501. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  32502. __decorate([
  32503. BABYLON.serialize(),
  32504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32505. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  32506. __decorate([
  32507. BABYLON.serialize(),
  32508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32509. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  32510. __decorate([
  32511. BABYLON.serializeAsTexture(),
  32512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  32513. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  32514. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  32515. })(BABYLON || (BABYLON = {}));
  32516. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  32517. var BABYLON;
  32518. (function (BABYLON) {
  32519. /**
  32520. * The PBR material of BJS following the specular glossiness convention.
  32521. *
  32522. * This fits to the PBR convention in the GLTF definition:
  32523. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  32524. */
  32525. var PBRSpecularGlossinessMaterial = (function (_super) {
  32526. __extends(PBRSpecularGlossinessMaterial, _super);
  32527. /**
  32528. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  32529. *
  32530. * @param name The material name
  32531. * @param scene The scene the material will be use in.
  32532. */
  32533. function PBRSpecularGlossinessMaterial(name, scene) {
  32534. var _this = _super.call(this, name, scene) || this;
  32535. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  32536. return _this;
  32537. }
  32538. /**
  32539. * Return the currrent class name of the material.
  32540. */
  32541. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  32542. return "PBRSpecularGlossinessMaterial";
  32543. };
  32544. /**
  32545. * Return the active textures of the material.
  32546. */
  32547. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  32548. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32549. if (this.diffuseTexture) {
  32550. activeTextures.push(this.diffuseTexture);
  32551. }
  32552. if (this.specularGlossinessTexture) {
  32553. activeTextures.push(this.specularGlossinessTexture);
  32554. }
  32555. return activeTextures;
  32556. };
  32557. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  32558. if (_super.prototype.hasTexture.call(this, texture)) {
  32559. return true;
  32560. }
  32561. if (this.diffuseTexture === texture) {
  32562. return true;
  32563. }
  32564. if (this.specularGlossinessTexture === texture) {
  32565. return true;
  32566. }
  32567. return false;
  32568. };
  32569. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  32570. var _this = this;
  32571. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  32572. };
  32573. /**
  32574. * Serialize the material to a parsable JSON object.
  32575. */
  32576. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  32577. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32578. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  32579. return serializationObject;
  32580. };
  32581. /**
  32582. * Parses a JSON object correponding to the serialize function.
  32583. */
  32584. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  32585. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  32586. };
  32587. return PBRSpecularGlossinessMaterial;
  32588. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  32589. __decorate([
  32590. BABYLON.serializeAsColor3("diffuse"),
  32591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  32592. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  32593. __decorate([
  32594. BABYLON.serializeAsTexture(),
  32595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  32596. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  32597. __decorate([
  32598. BABYLON.serializeAsColor3("specular"),
  32599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  32600. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  32601. __decorate([
  32602. BABYLON.serialize(),
  32603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  32604. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  32605. __decorate([
  32606. BABYLON.serializeAsTexture(),
  32607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  32608. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  32609. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  32610. })(BABYLON || (BABYLON = {}));
  32611. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  32612. var BABYLON;
  32613. (function (BABYLON) {
  32614. BABYLON.CameraInputTypes = {};
  32615. var CameraInputsManager = (function () {
  32616. function CameraInputsManager(camera) {
  32617. this.attached = {};
  32618. this.camera = camera;
  32619. this.checkInputs = function () { };
  32620. }
  32621. CameraInputsManager.prototype.add = function (input) {
  32622. var type = input.getSimpleName();
  32623. if (this.attached[type]) {
  32624. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  32625. return;
  32626. }
  32627. this.attached[type] = input;
  32628. input.camera = this.camera;
  32629. //for checkInputs, we are dynamically creating a function
  32630. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  32631. if (input.checkInputs) {
  32632. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  32633. }
  32634. if (this.attachedElement) {
  32635. input.attachControl(this.attachedElement);
  32636. }
  32637. };
  32638. CameraInputsManager.prototype.remove = function (inputToRemove) {
  32639. for (var cam in this.attached) {
  32640. var input = this.attached[cam];
  32641. if (input === inputToRemove) {
  32642. input.detachControl(this.attachedElement);
  32643. delete this.attached[cam];
  32644. this.rebuildInputCheck();
  32645. }
  32646. }
  32647. };
  32648. CameraInputsManager.prototype.removeByType = function (inputType) {
  32649. for (var cam in this.attached) {
  32650. var input = this.attached[cam];
  32651. if (input.getTypeName() === inputType) {
  32652. input.detachControl(this.attachedElement);
  32653. delete this.attached[cam];
  32654. this.rebuildInputCheck();
  32655. }
  32656. }
  32657. };
  32658. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  32659. var current = this.checkInputs;
  32660. return function () {
  32661. current();
  32662. fn();
  32663. };
  32664. };
  32665. CameraInputsManager.prototype.attachInput = function (input) {
  32666. input.attachControl(this.attachedElement, this.noPreventDefault);
  32667. };
  32668. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  32669. if (this.attachedElement) {
  32670. return;
  32671. }
  32672. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  32673. this.attachedElement = element;
  32674. this.noPreventDefault = noPreventDefault;
  32675. for (var cam in this.attached) {
  32676. var input = this.attached[cam];
  32677. this.attached[cam].attachControl(element, noPreventDefault);
  32678. }
  32679. };
  32680. CameraInputsManager.prototype.detachElement = function (element) {
  32681. if (this.attachedElement !== element) {
  32682. return;
  32683. }
  32684. for (var cam in this.attached) {
  32685. var input = this.attached[cam];
  32686. this.attached[cam].detachControl(element);
  32687. }
  32688. this.attachedElement = null;
  32689. };
  32690. CameraInputsManager.prototype.rebuildInputCheck = function () {
  32691. this.checkInputs = function () { };
  32692. for (var cam in this.attached) {
  32693. var input = this.attached[cam];
  32694. if (input.checkInputs) {
  32695. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  32696. }
  32697. }
  32698. };
  32699. CameraInputsManager.prototype.clear = function () {
  32700. if (this.attachedElement) {
  32701. this.detachElement(this.attachedElement);
  32702. }
  32703. this.attached = {};
  32704. this.attachedElement = null;
  32705. this.checkInputs = function () { };
  32706. };
  32707. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  32708. var inputs = {};
  32709. for (var cam in this.attached) {
  32710. var input = this.attached[cam];
  32711. var res = BABYLON.SerializationHelper.Serialize(input);
  32712. inputs[input.getTypeName()] = res;
  32713. }
  32714. serializedCamera.inputsmgr = inputs;
  32715. };
  32716. CameraInputsManager.prototype.parse = function (parsedCamera) {
  32717. var parsedInputs = parsedCamera.inputsmgr;
  32718. if (parsedInputs) {
  32719. this.clear();
  32720. for (var n in parsedInputs) {
  32721. var construct = BABYLON.CameraInputTypes[n];
  32722. if (construct) {
  32723. var parsedinput = parsedInputs[n];
  32724. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  32725. this.add(input);
  32726. }
  32727. }
  32728. }
  32729. else {
  32730. //2016-03-08 this part is for managing backward compatibility
  32731. for (var n in this.attached) {
  32732. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  32733. if (construct) {
  32734. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  32735. this.remove(this.attached[n]);
  32736. this.add(input);
  32737. }
  32738. }
  32739. }
  32740. };
  32741. return CameraInputsManager;
  32742. }());
  32743. BABYLON.CameraInputsManager = CameraInputsManager;
  32744. })(BABYLON || (BABYLON = {}));
  32745. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  32746. var BABYLON;
  32747. (function (BABYLON) {
  32748. var FreeCameraMouseInput = (function () {
  32749. function FreeCameraMouseInput(touchEnabled) {
  32750. if (touchEnabled === void 0) { touchEnabled = true; }
  32751. this.touchEnabled = touchEnabled;
  32752. this.buttons = [0, 1, 2];
  32753. this.angularSensibility = 2000.0;
  32754. }
  32755. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  32756. var _this = this;
  32757. var engine = this.camera.getEngine();
  32758. if (!this._pointerInput) {
  32759. this._pointerInput = function (p, s) {
  32760. var evt = p.event;
  32761. if (!_this.touchEnabled && evt.pointerType === "touch") {
  32762. return;
  32763. }
  32764. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32765. return;
  32766. }
  32767. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32768. try {
  32769. evt.srcElement.setPointerCapture(evt.pointerId);
  32770. }
  32771. catch (e) {
  32772. //Nothing to do with the error. Execution will continue.
  32773. }
  32774. _this.previousPosition = {
  32775. x: evt.clientX,
  32776. y: evt.clientY
  32777. };
  32778. if (!noPreventDefault) {
  32779. evt.preventDefault();
  32780. element.focus();
  32781. }
  32782. }
  32783. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32784. try {
  32785. evt.srcElement.releasePointerCapture(evt.pointerId);
  32786. }
  32787. catch (e) {
  32788. //Nothing to do with the error.
  32789. }
  32790. _this.previousPosition = null;
  32791. if (!noPreventDefault) {
  32792. evt.preventDefault();
  32793. }
  32794. }
  32795. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32796. if (!_this.previousPosition || engine.isPointerLock) {
  32797. return;
  32798. }
  32799. var offsetX = evt.clientX - _this.previousPosition.x;
  32800. var offsetY = evt.clientY - _this.previousPosition.y;
  32801. if (_this.camera.getScene().useRightHandedSystem) {
  32802. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  32803. }
  32804. else {
  32805. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  32806. }
  32807. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  32808. _this.previousPosition = {
  32809. x: evt.clientX,
  32810. y: evt.clientY
  32811. };
  32812. if (!noPreventDefault) {
  32813. evt.preventDefault();
  32814. }
  32815. }
  32816. };
  32817. }
  32818. this._onMouseMove = function (evt) {
  32819. if (!engine.isPointerLock) {
  32820. return;
  32821. }
  32822. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32823. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32824. if (_this.camera.getScene().useRightHandedSystem) {
  32825. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  32826. }
  32827. else {
  32828. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  32829. }
  32830. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  32831. _this.previousPosition = null;
  32832. if (!noPreventDefault) {
  32833. evt.preventDefault();
  32834. }
  32835. };
  32836. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  32837. element.addEventListener("mousemove", this._onMouseMove, false);
  32838. };
  32839. FreeCameraMouseInput.prototype.detachControl = function (element) {
  32840. if (this._observer && element) {
  32841. this.camera.getScene().onPointerObservable.remove(this._observer);
  32842. element.removeEventListener("mousemove", this._onMouseMove);
  32843. this._observer = null;
  32844. this._onMouseMove = null;
  32845. this.previousPosition = null;
  32846. }
  32847. };
  32848. FreeCameraMouseInput.prototype.getTypeName = function () {
  32849. return "FreeCameraMouseInput";
  32850. };
  32851. FreeCameraMouseInput.prototype.getSimpleName = function () {
  32852. return "mouse";
  32853. };
  32854. return FreeCameraMouseInput;
  32855. }());
  32856. __decorate([
  32857. BABYLON.serialize()
  32858. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  32859. __decorate([
  32860. BABYLON.serialize()
  32861. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  32862. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  32863. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  32864. })(BABYLON || (BABYLON = {}));
  32865. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  32866. var BABYLON;
  32867. (function (BABYLON) {
  32868. var FreeCameraKeyboardMoveInput = (function () {
  32869. function FreeCameraKeyboardMoveInput() {
  32870. this._keys = [];
  32871. this.keysUp = [38];
  32872. this.keysDown = [40];
  32873. this.keysLeft = [37];
  32874. this.keysRight = [39];
  32875. }
  32876. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32877. var _this = this;
  32878. if (!this._onKeyDown) {
  32879. element.tabIndex = 1;
  32880. this._onKeyDown = function (evt) {
  32881. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32882. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32883. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32884. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32885. var index = _this._keys.indexOf(evt.keyCode);
  32886. if (index === -1) {
  32887. _this._keys.push(evt.keyCode);
  32888. }
  32889. if (!noPreventDefault) {
  32890. evt.preventDefault();
  32891. }
  32892. }
  32893. };
  32894. this._onKeyUp = function (evt) {
  32895. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32896. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32897. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32898. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32899. var index = _this._keys.indexOf(evt.keyCode);
  32900. if (index >= 0) {
  32901. _this._keys.splice(index, 1);
  32902. }
  32903. if (!noPreventDefault) {
  32904. evt.preventDefault();
  32905. }
  32906. }
  32907. };
  32908. element.addEventListener("keydown", this._onKeyDown, false);
  32909. element.addEventListener("keyup", this._onKeyUp, false);
  32910. BABYLON.Tools.RegisterTopRootEvents([
  32911. { name: "blur", handler: this._onLostFocus }
  32912. ]);
  32913. }
  32914. };
  32915. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32916. if (this._onKeyDown) {
  32917. element.removeEventListener("keydown", this._onKeyDown);
  32918. element.removeEventListener("keyup", this._onKeyUp);
  32919. BABYLON.Tools.UnregisterTopRootEvents([
  32920. { name: "blur", handler: this._onLostFocus }
  32921. ]);
  32922. this._keys = [];
  32923. this._onKeyDown = null;
  32924. this._onKeyUp = null;
  32925. }
  32926. };
  32927. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32928. if (this._onKeyDown) {
  32929. var camera = this.camera;
  32930. // Keyboard
  32931. for (var index = 0; index < this._keys.length; index++) {
  32932. var keyCode = this._keys[index];
  32933. var speed = camera._computeLocalCameraSpeed();
  32934. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32935. camera._localDirection.copyFromFloats(-speed, 0, 0);
  32936. }
  32937. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32938. camera._localDirection.copyFromFloats(0, 0, speed);
  32939. }
  32940. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32941. camera._localDirection.copyFromFloats(speed, 0, 0);
  32942. }
  32943. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32944. camera._localDirection.copyFromFloats(0, 0, -speed);
  32945. }
  32946. if (camera.getScene().useRightHandedSystem) {
  32947. camera._localDirection.z *= -1;
  32948. }
  32949. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  32950. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  32951. camera.cameraDirection.addInPlace(camera._transformedDirection);
  32952. }
  32953. }
  32954. };
  32955. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32956. return "FreeCameraKeyboardMoveInput";
  32957. };
  32958. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  32959. this._keys = [];
  32960. };
  32961. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32962. return "keyboard";
  32963. };
  32964. return FreeCameraKeyboardMoveInput;
  32965. }());
  32966. __decorate([
  32967. BABYLON.serialize()
  32968. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32969. __decorate([
  32970. BABYLON.serialize()
  32971. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32972. __decorate([
  32973. BABYLON.serialize()
  32974. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32975. __decorate([
  32976. BABYLON.serialize()
  32977. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32978. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  32979. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  32980. })(BABYLON || (BABYLON = {}));
  32981. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  32982. var BABYLON;
  32983. (function (BABYLON) {
  32984. var FreeCameraInputsManager = (function (_super) {
  32985. __extends(FreeCameraInputsManager, _super);
  32986. function FreeCameraInputsManager(camera) {
  32987. return _super.call(this, camera) || this;
  32988. }
  32989. FreeCameraInputsManager.prototype.addKeyboard = function () {
  32990. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  32991. return this;
  32992. };
  32993. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  32994. if (touchEnabled === void 0) { touchEnabled = true; }
  32995. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  32996. return this;
  32997. };
  32998. FreeCameraInputsManager.prototype.addGamepad = function () {
  32999. this.add(new BABYLON.FreeCameraGamepadInput());
  33000. return this;
  33001. };
  33002. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  33003. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  33004. return this;
  33005. };
  33006. FreeCameraInputsManager.prototype.addTouch = function () {
  33007. this.add(new BABYLON.FreeCameraTouchInput());
  33008. return this;
  33009. };
  33010. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  33011. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  33012. return this;
  33013. };
  33014. return FreeCameraInputsManager;
  33015. }(BABYLON.CameraInputsManager));
  33016. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  33017. })(BABYLON || (BABYLON = {}));
  33018. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  33019. /// <reference path="babylon.camera.ts" />
  33020. var BABYLON;
  33021. (function (BABYLON) {
  33022. var TargetCamera = (function (_super) {
  33023. __extends(TargetCamera, _super);
  33024. function TargetCamera(name, position, scene) {
  33025. var _this = _super.call(this, name, position, scene) || this;
  33026. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  33027. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  33028. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  33029. _this.speed = 2.0;
  33030. _this.noRotationConstraint = false;
  33031. _this.lockedTarget = null;
  33032. _this._currentTarget = BABYLON.Vector3.Zero();
  33033. _this._viewMatrix = BABYLON.Matrix.Zero();
  33034. _this._camMatrix = BABYLON.Matrix.Zero();
  33035. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  33036. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  33037. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  33038. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  33039. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  33040. _this._lookAtTemp = BABYLON.Matrix.Zero();
  33041. _this._tempMatrix = BABYLON.Matrix.Zero();
  33042. return _this;
  33043. }
  33044. TargetCamera.prototype.getFrontPosition = function (distance) {
  33045. var direction = this.getTarget().subtract(this.position);
  33046. direction.normalize();
  33047. direction.scaleInPlace(distance);
  33048. return this.globalPosition.add(direction);
  33049. };
  33050. TargetCamera.prototype._getLockedTargetPosition = function () {
  33051. if (!this.lockedTarget) {
  33052. return null;
  33053. }
  33054. if (this.lockedTarget.absolutePosition) {
  33055. this.lockedTarget.computeWorldMatrix();
  33056. }
  33057. return this.lockedTarget.absolutePosition || this.lockedTarget;
  33058. };
  33059. // Cache
  33060. TargetCamera.prototype._initCache = function () {
  33061. _super.prototype._initCache.call(this);
  33062. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33063. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33064. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33065. };
  33066. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  33067. if (!ignoreParentClass) {
  33068. _super.prototype._updateCache.call(this);
  33069. }
  33070. var lockedTargetPosition = this._getLockedTargetPosition();
  33071. if (!lockedTargetPosition) {
  33072. this._cache.lockedTarget = null;
  33073. }
  33074. else {
  33075. if (!this._cache.lockedTarget) {
  33076. this._cache.lockedTarget = lockedTargetPosition.clone();
  33077. }
  33078. else {
  33079. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  33080. }
  33081. }
  33082. this._cache.rotation.copyFrom(this.rotation);
  33083. if (this.rotationQuaternion)
  33084. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33085. };
  33086. // Synchronized
  33087. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  33088. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  33089. return false;
  33090. }
  33091. var lockedTargetPosition = this._getLockedTargetPosition();
  33092. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  33093. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  33094. };
  33095. // Methods
  33096. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  33097. var engine = this.getEngine();
  33098. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  33099. };
  33100. // Target
  33101. TargetCamera.prototype.setTarget = function (target) {
  33102. this.upVector.normalize();
  33103. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  33104. this._camMatrix.invert();
  33105. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  33106. var vDir = target.subtract(this.position);
  33107. if (vDir.x >= 0.0) {
  33108. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  33109. }
  33110. else {
  33111. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  33112. }
  33113. this.rotation.z = 0;
  33114. if (isNaN(this.rotation.x)) {
  33115. this.rotation.x = 0;
  33116. }
  33117. if (isNaN(this.rotation.y)) {
  33118. this.rotation.y = 0;
  33119. }
  33120. if (isNaN(this.rotation.z)) {
  33121. this.rotation.z = 0;
  33122. }
  33123. if (this.rotationQuaternion) {
  33124. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  33125. }
  33126. };
  33127. /**
  33128. * Return the current target position of the camera. This value is expressed in local space.
  33129. */
  33130. TargetCamera.prototype.getTarget = function () {
  33131. return this._currentTarget;
  33132. };
  33133. TargetCamera.prototype._decideIfNeedsToMove = function () {
  33134. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  33135. };
  33136. TargetCamera.prototype._updatePosition = function () {
  33137. if (this.parent) {
  33138. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  33139. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  33140. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  33141. return;
  33142. }
  33143. this.position.addInPlace(this.cameraDirection);
  33144. };
  33145. TargetCamera.prototype._checkInputs = function () {
  33146. var needToMove = this._decideIfNeedsToMove();
  33147. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  33148. // Move
  33149. if (needToMove) {
  33150. this._updatePosition();
  33151. }
  33152. // Rotate
  33153. if (needToRotate) {
  33154. this.rotation.x += this.cameraRotation.x;
  33155. this.rotation.y += this.cameraRotation.y;
  33156. //rotate, if quaternion is set and rotation was used
  33157. if (this.rotationQuaternion) {
  33158. var len = this.rotation.lengthSquared();
  33159. if (len) {
  33160. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  33161. }
  33162. }
  33163. if (!this.noRotationConstraint) {
  33164. var limit = (Math.PI / 2) * 0.95;
  33165. if (this.rotation.x > limit)
  33166. this.rotation.x = limit;
  33167. if (this.rotation.x < -limit)
  33168. this.rotation.x = -limit;
  33169. }
  33170. }
  33171. // Inertia
  33172. if (needToMove) {
  33173. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  33174. this.cameraDirection.x = 0;
  33175. }
  33176. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  33177. this.cameraDirection.y = 0;
  33178. }
  33179. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  33180. this.cameraDirection.z = 0;
  33181. }
  33182. this.cameraDirection.scaleInPlace(this.inertia);
  33183. }
  33184. if (needToRotate) {
  33185. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  33186. this.cameraRotation.x = 0;
  33187. }
  33188. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  33189. this.cameraRotation.y = 0;
  33190. }
  33191. this.cameraRotation.scaleInPlace(this.inertia);
  33192. }
  33193. _super.prototype._checkInputs.call(this);
  33194. };
  33195. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  33196. if (this.rotationQuaternion) {
  33197. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  33198. //update the up vector!
  33199. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  33200. }
  33201. else {
  33202. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  33203. }
  33204. };
  33205. TargetCamera.prototype._getViewMatrix = function () {
  33206. if (!this.lockedTarget) {
  33207. // Compute
  33208. this._updateCameraRotationMatrix();
  33209. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  33210. // Computing target and final matrix
  33211. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  33212. }
  33213. else {
  33214. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  33215. }
  33216. if (this.getScene().useRightHandedSystem) {
  33217. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  33218. }
  33219. else {
  33220. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  33221. }
  33222. return this._viewMatrix;
  33223. };
  33224. /**
  33225. * @override
  33226. * Override Camera.createRigCamera
  33227. */
  33228. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  33229. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  33230. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  33231. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  33232. if (!this.rotationQuaternion) {
  33233. this.rotationQuaternion = new BABYLON.Quaternion();
  33234. }
  33235. rigCamera._cameraRigParams = {};
  33236. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  33237. }
  33238. return rigCamera;
  33239. }
  33240. return null;
  33241. };
  33242. /**
  33243. * @override
  33244. * Override Camera._updateRigCameras
  33245. */
  33246. TargetCamera.prototype._updateRigCameras = function () {
  33247. var camLeft = this._rigCameras[0];
  33248. var camRight = this._rigCameras[1];
  33249. switch (this.cameraRigMode) {
  33250. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33251. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33252. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33253. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33254. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  33255. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  33256. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  33257. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  33258. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  33259. camLeft.setTarget(this.getTarget());
  33260. camRight.setTarget(this.getTarget());
  33261. break;
  33262. case BABYLON.Camera.RIG_MODE_VR:
  33263. if (camLeft.rotationQuaternion) {
  33264. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33265. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33266. }
  33267. else {
  33268. camLeft.rotation.copyFrom(this.rotation);
  33269. camRight.rotation.copyFrom(this.rotation);
  33270. }
  33271. camLeft.position.copyFrom(this.position);
  33272. camRight.position.copyFrom(this.position);
  33273. break;
  33274. }
  33275. _super.prototype._updateRigCameras.call(this);
  33276. };
  33277. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  33278. if (!this._rigCamTransformMatrix) {
  33279. this._rigCamTransformMatrix = new BABYLON.Matrix();
  33280. }
  33281. var target = this.getTarget();
  33282. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  33283. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  33284. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  33285. };
  33286. TargetCamera.prototype.getClassName = function () {
  33287. return "TargetCamera";
  33288. };
  33289. return TargetCamera;
  33290. }(BABYLON.Camera));
  33291. __decorate([
  33292. BABYLON.serializeAsVector3()
  33293. ], TargetCamera.prototype, "rotation", void 0);
  33294. __decorate([
  33295. BABYLON.serialize()
  33296. ], TargetCamera.prototype, "speed", void 0);
  33297. __decorate([
  33298. BABYLON.serializeAsMeshReference("lockedTargetId")
  33299. ], TargetCamera.prototype, "lockedTarget", void 0);
  33300. BABYLON.TargetCamera = TargetCamera;
  33301. })(BABYLON || (BABYLON = {}));
  33302. //# sourceMappingURL=babylon.targetCamera.js.map
  33303. var BABYLON;
  33304. (function (BABYLON) {
  33305. var FreeCamera = (function (_super) {
  33306. __extends(FreeCamera, _super);
  33307. function FreeCamera(name, position, scene) {
  33308. var _this = _super.call(this, name, position, scene) || this;
  33309. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  33310. _this.checkCollisions = false;
  33311. _this.applyGravity = false;
  33312. _this._needMoveForGravity = false;
  33313. _this._oldPosition = BABYLON.Vector3.Zero();
  33314. _this._diffPosition = BABYLON.Vector3.Zero();
  33315. _this._newPosition = BABYLON.Vector3.Zero();
  33316. // Collisions
  33317. _this._collisionMask = -1;
  33318. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  33319. if (collidedMesh === void 0) { collidedMesh = null; }
  33320. //TODO move this to the collision coordinator!
  33321. if (_this.getScene().workerCollisions)
  33322. newPosition.multiplyInPlace(_this._collider.radius);
  33323. var updatePosition = function (newPos) {
  33324. _this._newPosition.copyFrom(newPos);
  33325. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  33326. var oldPosition = _this.position.clone();
  33327. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  33328. _this.position.addInPlace(_this._diffPosition);
  33329. if (_this.onCollide && collidedMesh) {
  33330. _this.onCollide(collidedMesh);
  33331. }
  33332. }
  33333. };
  33334. updatePosition(newPosition);
  33335. };
  33336. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  33337. _this.inputs.addKeyboard().addMouse();
  33338. return _this;
  33339. }
  33340. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  33341. //-- begin properties for backward compatibility for inputs
  33342. get: function () {
  33343. var mouse = this.inputs.attached["mouse"];
  33344. if (mouse)
  33345. return mouse.angularSensibility;
  33346. },
  33347. set: function (value) {
  33348. var mouse = this.inputs.attached["mouse"];
  33349. if (mouse)
  33350. mouse.angularSensibility = value;
  33351. },
  33352. enumerable: true,
  33353. configurable: true
  33354. });
  33355. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  33356. get: function () {
  33357. var keyboard = this.inputs.attached["keyboard"];
  33358. if (keyboard)
  33359. return keyboard.keysUp;
  33360. },
  33361. set: function (value) {
  33362. var keyboard = this.inputs.attached["keyboard"];
  33363. if (keyboard)
  33364. keyboard.keysUp = value;
  33365. },
  33366. enumerable: true,
  33367. configurable: true
  33368. });
  33369. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  33370. get: function () {
  33371. var keyboard = this.inputs.attached["keyboard"];
  33372. if (keyboard)
  33373. return keyboard.keysDown;
  33374. },
  33375. set: function (value) {
  33376. var keyboard = this.inputs.attached["keyboard"];
  33377. if (keyboard)
  33378. keyboard.keysDown = value;
  33379. },
  33380. enumerable: true,
  33381. configurable: true
  33382. });
  33383. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  33384. get: function () {
  33385. var keyboard = this.inputs.attached["keyboard"];
  33386. if (keyboard)
  33387. return keyboard.keysLeft;
  33388. },
  33389. set: function (value) {
  33390. var keyboard = this.inputs.attached["keyboard"];
  33391. if (keyboard)
  33392. keyboard.keysLeft = value;
  33393. },
  33394. enumerable: true,
  33395. configurable: true
  33396. });
  33397. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  33398. get: function () {
  33399. var keyboard = this.inputs.attached["keyboard"];
  33400. if (keyboard)
  33401. return keyboard.keysRight;
  33402. },
  33403. set: function (value) {
  33404. var keyboard = this.inputs.attached["keyboard"];
  33405. if (keyboard)
  33406. keyboard.keysRight = value;
  33407. },
  33408. enumerable: true,
  33409. configurable: true
  33410. });
  33411. // Controls
  33412. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33413. this.inputs.attachElement(element, noPreventDefault);
  33414. };
  33415. FreeCamera.prototype.detachControl = function (element) {
  33416. this.inputs.detachElement(element);
  33417. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  33418. this.cameraRotation = new BABYLON.Vector2(0, 0);
  33419. };
  33420. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  33421. get: function () {
  33422. return this._collisionMask;
  33423. },
  33424. set: function (mask) {
  33425. this._collisionMask = !isNaN(mask) ? mask : -1;
  33426. },
  33427. enumerable: true,
  33428. configurable: true
  33429. });
  33430. FreeCamera.prototype._collideWithWorld = function (velocity) {
  33431. var globalPosition;
  33432. if (this.parent) {
  33433. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  33434. }
  33435. else {
  33436. globalPosition = this.position;
  33437. }
  33438. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  33439. if (!this._collider) {
  33440. this._collider = new BABYLON.Collider();
  33441. }
  33442. this._collider.radius = this.ellipsoid;
  33443. this._collider.collisionMask = this._collisionMask;
  33444. //no need for clone, as long as gravity is not on.
  33445. var actualVelocity = velocity;
  33446. //add gravity to the velocity to prevent the dual-collision checking
  33447. if (this.applyGravity) {
  33448. //this prevents mending with cameraDirection, a global variable of the free camera class.
  33449. actualVelocity = velocity.add(this.getScene().gravity);
  33450. }
  33451. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  33452. };
  33453. FreeCamera.prototype._checkInputs = function () {
  33454. if (!this._localDirection) {
  33455. this._localDirection = BABYLON.Vector3.Zero();
  33456. this._transformedDirection = BABYLON.Vector3.Zero();
  33457. }
  33458. this.inputs.checkInputs();
  33459. _super.prototype._checkInputs.call(this);
  33460. };
  33461. FreeCamera.prototype._decideIfNeedsToMove = function () {
  33462. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  33463. };
  33464. FreeCamera.prototype._updatePosition = function () {
  33465. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  33466. this._collideWithWorld(this.cameraDirection);
  33467. }
  33468. else {
  33469. _super.prototype._updatePosition.call(this);
  33470. }
  33471. };
  33472. FreeCamera.prototype.dispose = function () {
  33473. this.inputs.clear();
  33474. _super.prototype.dispose.call(this);
  33475. };
  33476. FreeCamera.prototype.getClassName = function () {
  33477. return "FreeCamera";
  33478. };
  33479. return FreeCamera;
  33480. }(BABYLON.TargetCamera));
  33481. __decorate([
  33482. BABYLON.serializeAsVector3()
  33483. ], FreeCamera.prototype, "ellipsoid", void 0);
  33484. __decorate([
  33485. BABYLON.serialize()
  33486. ], FreeCamera.prototype, "checkCollisions", void 0);
  33487. __decorate([
  33488. BABYLON.serialize()
  33489. ], FreeCamera.prototype, "applyGravity", void 0);
  33490. BABYLON.FreeCamera = FreeCamera;
  33491. })(BABYLON || (BABYLON = {}));
  33492. //# sourceMappingURL=babylon.freeCamera.js.map
  33493. var BABYLON;
  33494. (function (BABYLON) {
  33495. var ArcRotateCameraKeyboardMoveInput = (function () {
  33496. function ArcRotateCameraKeyboardMoveInput() {
  33497. this._keys = [];
  33498. this.keysUp = [38];
  33499. this.keysDown = [40];
  33500. this.keysLeft = [37];
  33501. this.keysRight = [39];
  33502. }
  33503. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  33504. var _this = this;
  33505. element.tabIndex = 1;
  33506. this._onKeyDown = function (evt) {
  33507. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33508. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33509. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33510. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33511. var index = _this._keys.indexOf(evt.keyCode);
  33512. if (index === -1) {
  33513. _this._keys.push(evt.keyCode);
  33514. }
  33515. if (evt.preventDefault) {
  33516. if (!noPreventDefault) {
  33517. evt.preventDefault();
  33518. }
  33519. }
  33520. }
  33521. };
  33522. this._onKeyUp = function (evt) {
  33523. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33524. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33525. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33526. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33527. var index = _this._keys.indexOf(evt.keyCode);
  33528. if (index >= 0) {
  33529. _this._keys.splice(index, 1);
  33530. }
  33531. if (evt.preventDefault) {
  33532. if (!noPreventDefault) {
  33533. evt.preventDefault();
  33534. }
  33535. }
  33536. }
  33537. };
  33538. this._onLostFocus = function () {
  33539. _this._keys = [];
  33540. };
  33541. element.addEventListener("keydown", this._onKeyDown, false);
  33542. element.addEventListener("keyup", this._onKeyUp, false);
  33543. BABYLON.Tools.RegisterTopRootEvents([
  33544. { name: "blur", handler: this._onLostFocus }
  33545. ]);
  33546. };
  33547. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  33548. if (element) {
  33549. element.removeEventListener("keydown", this._onKeyDown);
  33550. element.removeEventListener("keyup", this._onKeyUp);
  33551. }
  33552. BABYLON.Tools.UnregisterTopRootEvents([
  33553. { name: "blur", handler: this._onLostFocus }
  33554. ]);
  33555. this._keys = [];
  33556. this._onKeyDown = null;
  33557. this._onKeyUp = null;
  33558. this._onLostFocus = null;
  33559. };
  33560. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  33561. if (this._onKeyDown) {
  33562. var camera = this.camera;
  33563. for (var index = 0; index < this._keys.length; index++) {
  33564. var keyCode = this._keys[index];
  33565. if (this.keysLeft.indexOf(keyCode) !== -1) {
  33566. camera.inertialAlphaOffset -= 0.01;
  33567. }
  33568. else if (this.keysUp.indexOf(keyCode) !== -1) {
  33569. camera.inertialBetaOffset -= 0.01;
  33570. }
  33571. else if (this.keysRight.indexOf(keyCode) !== -1) {
  33572. camera.inertialAlphaOffset += 0.01;
  33573. }
  33574. else if (this.keysDown.indexOf(keyCode) !== -1) {
  33575. camera.inertialBetaOffset += 0.01;
  33576. }
  33577. }
  33578. }
  33579. };
  33580. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  33581. return "ArcRotateCameraKeyboardMoveInput";
  33582. };
  33583. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  33584. return "keyboard";
  33585. };
  33586. return ArcRotateCameraKeyboardMoveInput;
  33587. }());
  33588. __decorate([
  33589. BABYLON.serialize()
  33590. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  33591. __decorate([
  33592. BABYLON.serialize()
  33593. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  33594. __decorate([
  33595. BABYLON.serialize()
  33596. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  33597. __decorate([
  33598. BABYLON.serialize()
  33599. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  33600. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  33601. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  33602. })(BABYLON || (BABYLON = {}));
  33603. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  33604. var BABYLON;
  33605. (function (BABYLON) {
  33606. var ArcRotateCameraMouseWheelInput = (function () {
  33607. function ArcRotateCameraMouseWheelInput() {
  33608. this.wheelPrecision = 3.0;
  33609. }
  33610. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  33611. var _this = this;
  33612. this._wheel = function (p, s) {
  33613. //sanity check - this should be a PointerWheel event.
  33614. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  33615. return;
  33616. var event = p.event;
  33617. var delta = 0;
  33618. if (event.wheelDelta) {
  33619. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  33620. }
  33621. else if (event.detail) {
  33622. delta = -event.detail / _this.wheelPrecision;
  33623. }
  33624. if (delta)
  33625. _this.camera.inertialRadiusOffset += delta;
  33626. if (event.preventDefault) {
  33627. if (!noPreventDefault) {
  33628. event.preventDefault();
  33629. }
  33630. }
  33631. };
  33632. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  33633. };
  33634. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  33635. if (this._observer && element) {
  33636. this.camera.getScene().onPointerObservable.remove(this._observer);
  33637. this._observer = null;
  33638. this._wheel = null;
  33639. }
  33640. };
  33641. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  33642. return "ArcRotateCameraMouseWheelInput";
  33643. };
  33644. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  33645. return "mousewheel";
  33646. };
  33647. return ArcRotateCameraMouseWheelInput;
  33648. }());
  33649. __decorate([
  33650. BABYLON.serialize()
  33651. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  33652. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  33653. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  33654. })(BABYLON || (BABYLON = {}));
  33655. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  33656. var BABYLON;
  33657. (function (BABYLON) {
  33658. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  33659. var ArcRotateCameraPointersInput = (function () {
  33660. function ArcRotateCameraPointersInput() {
  33661. this.buttons = [0, 1, 2];
  33662. this.angularSensibilityX = 1000.0;
  33663. this.angularSensibilityY = 1000.0;
  33664. this.pinchPrecision = 6.0;
  33665. this.panningSensibility = 50.0;
  33666. this._isPanClick = false;
  33667. this.pinchInwards = true;
  33668. }
  33669. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  33670. var _this = this;
  33671. var engine = this.camera.getEngine();
  33672. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  33673. var pointA, pointB;
  33674. var previousPinchDistance = 0;
  33675. this._pointerInput = function (p, s) {
  33676. var evt = p.event;
  33677. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  33678. return;
  33679. }
  33680. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  33681. try {
  33682. evt.srcElement.setPointerCapture(evt.pointerId);
  33683. }
  33684. catch (e) {
  33685. //Nothing to do with the error. Execution will continue.
  33686. }
  33687. // Manage panning with pan button click
  33688. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  33689. // manage pointers
  33690. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  33691. if (pointA === undefined) {
  33692. pointA = cacheSoloPointer;
  33693. }
  33694. else if (pointB === undefined) {
  33695. pointB = cacheSoloPointer;
  33696. }
  33697. if (!noPreventDefault) {
  33698. evt.preventDefault();
  33699. element.focus();
  33700. }
  33701. }
  33702. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  33703. try {
  33704. evt.srcElement.releasePointerCapture(evt.pointerId);
  33705. }
  33706. catch (e) {
  33707. //Nothing to do with the error.
  33708. }
  33709. cacheSoloPointer = null;
  33710. previousPinchDistance = 0;
  33711. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  33712. //but emptying completly pointers collection is required to fix a bug on iPhone :
  33713. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  33714. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  33715. pointA = pointB = undefined;
  33716. if (!noPreventDefault) {
  33717. evt.preventDefault();
  33718. }
  33719. }
  33720. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  33721. if (!noPreventDefault) {
  33722. evt.preventDefault();
  33723. }
  33724. // One button down
  33725. if (pointA && pointB === undefined) {
  33726. if (_this.panningSensibility !== 0 &&
  33727. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  33728. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  33729. _this.camera
  33730. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  33731. _this.camera
  33732. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  33733. }
  33734. else {
  33735. var offsetX = evt.clientX - cacheSoloPointer.x;
  33736. var offsetY = evt.clientY - cacheSoloPointer.y;
  33737. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  33738. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  33739. }
  33740. cacheSoloPointer.x = evt.clientX;
  33741. cacheSoloPointer.y = evt.clientY;
  33742. }
  33743. else if (pointA && pointB) {
  33744. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  33745. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  33746. ed.x = evt.clientX;
  33747. ed.y = evt.clientY;
  33748. var direction = _this.pinchInwards ? 1 : -1;
  33749. var distX = pointA.x - pointB.x;
  33750. var distY = pointA.y - pointB.y;
  33751. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  33752. if (previousPinchDistance === 0) {
  33753. previousPinchDistance = pinchSquaredDistance;
  33754. return;
  33755. }
  33756. if (pinchSquaredDistance !== previousPinchDistance) {
  33757. _this.camera
  33758. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  33759. (_this.pinchPrecision *
  33760. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  33761. direction);
  33762. previousPinchDistance = pinchSquaredDistance;
  33763. }
  33764. }
  33765. }
  33766. };
  33767. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  33768. this._onContextMenu = function (evt) {
  33769. evt.preventDefault();
  33770. };
  33771. if (!this.camera._useCtrlForPanning) {
  33772. element.addEventListener("contextmenu", this._onContextMenu, false);
  33773. }
  33774. this._onLostFocus = function () {
  33775. //this._keys = [];
  33776. pointA = pointB = undefined;
  33777. previousPinchDistance = 0;
  33778. cacheSoloPointer = null;
  33779. };
  33780. this._onMouseMove = function (evt) {
  33781. if (!engine.isPointerLock) {
  33782. return;
  33783. }
  33784. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  33785. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  33786. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  33787. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  33788. if (!noPreventDefault) {
  33789. evt.preventDefault();
  33790. }
  33791. };
  33792. this._onGestureStart = function (e) {
  33793. if (window.MSGesture === undefined) {
  33794. return;
  33795. }
  33796. if (!_this._MSGestureHandler) {
  33797. _this._MSGestureHandler = new MSGesture();
  33798. _this._MSGestureHandler.target = element;
  33799. }
  33800. _this._MSGestureHandler.addPointer(e.pointerId);
  33801. };
  33802. this._onGesture = function (e) {
  33803. _this.camera.radius *= e.scale;
  33804. if (e.preventDefault) {
  33805. if (!noPreventDefault) {
  33806. e.stopPropagation();
  33807. e.preventDefault();
  33808. }
  33809. }
  33810. };
  33811. element.addEventListener("mousemove", this._onMouseMove, false);
  33812. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  33813. element.addEventListener("MSGestureChange", this._onGesture, false);
  33814. BABYLON.Tools.RegisterTopRootEvents([
  33815. { name: "blur", handler: this._onLostFocus }
  33816. ]);
  33817. };
  33818. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  33819. if (element && this._observer) {
  33820. this.camera.getScene().onPointerObservable.remove(this._observer);
  33821. this._observer = null;
  33822. element.removeEventListener("contextmenu", this._onContextMenu);
  33823. element.removeEventListener("mousemove", this._onMouseMove);
  33824. element.removeEventListener("MSPointerDown", this._onGestureStart);
  33825. element.removeEventListener("MSGestureChange", this._onGesture);
  33826. this._isPanClick = false;
  33827. this.pinchInwards = true;
  33828. this._onMouseMove = null;
  33829. this._onGestureStart = null;
  33830. this._onGesture = null;
  33831. this._MSGestureHandler = null;
  33832. this._onLostFocus = null;
  33833. this._onContextMenu = null;
  33834. }
  33835. BABYLON.Tools.UnregisterTopRootEvents([
  33836. { name: "blur", handler: this._onLostFocus }
  33837. ]);
  33838. };
  33839. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  33840. return "ArcRotateCameraPointersInput";
  33841. };
  33842. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  33843. return "pointers";
  33844. };
  33845. return ArcRotateCameraPointersInput;
  33846. }());
  33847. __decorate([
  33848. BABYLON.serialize()
  33849. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  33850. __decorate([
  33851. BABYLON.serialize()
  33852. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  33853. __decorate([
  33854. BABYLON.serialize()
  33855. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  33856. __decorate([
  33857. BABYLON.serialize()
  33858. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  33859. __decorate([
  33860. BABYLON.serialize()
  33861. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  33862. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  33863. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  33864. })(BABYLON || (BABYLON = {}));
  33865. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  33866. /// <reference path="babylon.targetCamera.ts" />
  33867. /// <reference path="..\Tools\babylon.tools.ts" />
  33868. var BABYLON;
  33869. (function (BABYLON) {
  33870. var ArcRotateCamera = (function (_super) {
  33871. __extends(ArcRotateCamera, _super);
  33872. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  33873. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  33874. _this.inertialAlphaOffset = 0;
  33875. _this.inertialBetaOffset = 0;
  33876. _this.inertialRadiusOffset = 0;
  33877. _this.lowerAlphaLimit = null;
  33878. _this.upperAlphaLimit = null;
  33879. _this.lowerBetaLimit = 0.01;
  33880. _this.upperBetaLimit = Math.PI;
  33881. _this.lowerRadiusLimit = null;
  33882. _this.upperRadiusLimit = null;
  33883. _this.inertialPanningX = 0;
  33884. _this.inertialPanningY = 0;
  33885. _this.panningInertia = 0.9;
  33886. //-- end properties for backward compatibility for inputs
  33887. _this.zoomOnFactor = 1;
  33888. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  33889. _this.allowUpsideDown = true;
  33890. _this._viewMatrix = new BABYLON.Matrix();
  33891. // Panning
  33892. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  33893. _this.checkCollisions = false;
  33894. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  33895. _this._previousPosition = BABYLON.Vector3.Zero();
  33896. _this._collisionVelocity = BABYLON.Vector3.Zero();
  33897. _this._newPosition = BABYLON.Vector3.Zero();
  33898. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  33899. if (collidedMesh === void 0) { collidedMesh = null; }
  33900. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  33901. newPosition.multiplyInPlace(_this._collider.radius);
  33902. }
  33903. if (!collidedMesh) {
  33904. _this._previousPosition.copyFrom(_this.position);
  33905. }
  33906. else {
  33907. _this.setPosition(newPosition);
  33908. if (_this.onCollide) {
  33909. _this.onCollide(collidedMesh);
  33910. }
  33911. }
  33912. // Recompute because of constraints
  33913. var cosa = Math.cos(_this.alpha);
  33914. var sina = Math.sin(_this.alpha);
  33915. var cosb = Math.cos(_this.beta);
  33916. var sinb = Math.sin(_this.beta);
  33917. if (sinb === 0) {
  33918. sinb = 0.0001;
  33919. }
  33920. var target = _this._getTargetPosition();
  33921. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  33922. _this.position.copyFrom(_this._newPosition);
  33923. var up = _this.upVector;
  33924. if (_this.allowUpsideDown && _this.beta < 0) {
  33925. up = up.clone();
  33926. up = up.negate();
  33927. }
  33928. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  33929. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  33930. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  33931. _this._collisionTriggered = false;
  33932. };
  33933. _this._target = BABYLON.Vector3.Zero();
  33934. if (target) {
  33935. _this.setTarget(target);
  33936. }
  33937. _this.alpha = alpha;
  33938. _this.beta = beta;
  33939. _this.radius = radius;
  33940. _this.getViewMatrix();
  33941. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  33942. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  33943. return _this;
  33944. }
  33945. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  33946. get: function () {
  33947. return this._target;
  33948. },
  33949. set: function (value) {
  33950. this.setTarget(value);
  33951. },
  33952. enumerable: true,
  33953. configurable: true
  33954. });
  33955. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  33956. //-- begin properties for backward compatibility for inputs
  33957. get: function () {
  33958. var pointers = this.inputs.attached["pointers"];
  33959. if (pointers)
  33960. return pointers.angularSensibilityX;
  33961. },
  33962. set: function (value) {
  33963. var pointers = this.inputs.attached["pointers"];
  33964. if (pointers) {
  33965. pointers.angularSensibilityX = value;
  33966. }
  33967. },
  33968. enumerable: true,
  33969. configurable: true
  33970. });
  33971. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  33972. get: function () {
  33973. var pointers = this.inputs.attached["pointers"];
  33974. if (pointers)
  33975. return pointers.angularSensibilityY;
  33976. },
  33977. set: function (value) {
  33978. var pointers = this.inputs.attached["pointers"];
  33979. if (pointers) {
  33980. pointers.angularSensibilityY = value;
  33981. }
  33982. },
  33983. enumerable: true,
  33984. configurable: true
  33985. });
  33986. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  33987. get: function () {
  33988. var pointers = this.inputs.attached["pointers"];
  33989. if (pointers)
  33990. return pointers.pinchPrecision;
  33991. },
  33992. set: function (value) {
  33993. var pointers = this.inputs.attached["pointers"];
  33994. if (pointers) {
  33995. pointers.pinchPrecision = value;
  33996. }
  33997. },
  33998. enumerable: true,
  33999. configurable: true
  34000. });
  34001. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  34002. get: function () {
  34003. var pointers = this.inputs.attached["pointers"];
  34004. if (pointers)
  34005. return pointers.panningSensibility;
  34006. },
  34007. set: function (value) {
  34008. var pointers = this.inputs.attached["pointers"];
  34009. if (pointers) {
  34010. pointers.panningSensibility = value;
  34011. }
  34012. },
  34013. enumerable: true,
  34014. configurable: true
  34015. });
  34016. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  34017. get: function () {
  34018. var keyboard = this.inputs.attached["keyboard"];
  34019. if (keyboard)
  34020. return keyboard.keysUp;
  34021. },
  34022. set: function (value) {
  34023. var keyboard = this.inputs.attached["keyboard"];
  34024. if (keyboard)
  34025. keyboard.keysUp = value;
  34026. },
  34027. enumerable: true,
  34028. configurable: true
  34029. });
  34030. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  34031. get: function () {
  34032. var keyboard = this.inputs.attached["keyboard"];
  34033. if (keyboard)
  34034. return keyboard.keysDown;
  34035. },
  34036. set: function (value) {
  34037. var keyboard = this.inputs.attached["keyboard"];
  34038. if (keyboard)
  34039. keyboard.keysDown = value;
  34040. },
  34041. enumerable: true,
  34042. configurable: true
  34043. });
  34044. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  34045. get: function () {
  34046. var keyboard = this.inputs.attached["keyboard"];
  34047. if (keyboard)
  34048. return keyboard.keysLeft;
  34049. },
  34050. set: function (value) {
  34051. var keyboard = this.inputs.attached["keyboard"];
  34052. if (keyboard)
  34053. keyboard.keysLeft = value;
  34054. },
  34055. enumerable: true,
  34056. configurable: true
  34057. });
  34058. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  34059. get: function () {
  34060. var keyboard = this.inputs.attached["keyboard"];
  34061. if (keyboard)
  34062. return keyboard.keysRight;
  34063. },
  34064. set: function (value) {
  34065. var keyboard = this.inputs.attached["keyboard"];
  34066. if (keyboard)
  34067. keyboard.keysRight = value;
  34068. },
  34069. enumerable: true,
  34070. configurable: true
  34071. });
  34072. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  34073. get: function () {
  34074. var mousewheel = this.inputs.attached["mousewheel"];
  34075. if (mousewheel)
  34076. return mousewheel.wheelPrecision;
  34077. },
  34078. set: function (value) {
  34079. var mousewheel = this.inputs.attached["mousewheel"];
  34080. if (mousewheel)
  34081. mousewheel.wheelPrecision = value;
  34082. },
  34083. enumerable: true,
  34084. configurable: true
  34085. });
  34086. // Cache
  34087. ArcRotateCamera.prototype._initCache = function () {
  34088. _super.prototype._initCache.call(this);
  34089. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34090. this._cache.alpha = undefined;
  34091. this._cache.beta = undefined;
  34092. this._cache.radius = undefined;
  34093. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  34094. };
  34095. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  34096. if (!ignoreParentClass) {
  34097. _super.prototype._updateCache.call(this);
  34098. }
  34099. this._cache._target.copyFrom(this._getTargetPosition());
  34100. this._cache.alpha = this.alpha;
  34101. this._cache.beta = this.beta;
  34102. this._cache.radius = this.radius;
  34103. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  34104. };
  34105. ArcRotateCamera.prototype._getTargetPosition = function () {
  34106. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  34107. var pos = this._targetHost.getAbsolutePosition();
  34108. if (this._targetBoundingCenter) {
  34109. pos.addToRef(this._targetBoundingCenter, this._target);
  34110. }
  34111. else {
  34112. this._target.copyFrom(pos);
  34113. }
  34114. }
  34115. var lockedTargetPosition = this._getLockedTargetPosition();
  34116. if (lockedTargetPosition) {
  34117. return lockedTargetPosition;
  34118. }
  34119. return this._target;
  34120. };
  34121. // Synchronized
  34122. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  34123. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  34124. return false;
  34125. return this._cache._target.equals(this._getTargetPosition())
  34126. && this._cache.alpha === this.alpha
  34127. && this._cache.beta === this.beta
  34128. && this._cache.radius === this.radius
  34129. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  34130. };
  34131. // Methods
  34132. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  34133. var _this = this;
  34134. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  34135. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  34136. this._useCtrlForPanning = useCtrlForPanning;
  34137. this._panningMouseButton = panningMouseButton;
  34138. this.inputs.attachElement(element, noPreventDefault);
  34139. this._reset = function () {
  34140. _this.inertialAlphaOffset = 0;
  34141. _this.inertialBetaOffset = 0;
  34142. _this.inertialRadiusOffset = 0;
  34143. };
  34144. };
  34145. ArcRotateCamera.prototype.detachControl = function (element) {
  34146. this.inputs.detachElement(element);
  34147. if (this._reset) {
  34148. this._reset();
  34149. }
  34150. };
  34151. ArcRotateCamera.prototype._checkInputs = function () {
  34152. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  34153. if (this._collisionTriggered) {
  34154. return;
  34155. }
  34156. this.inputs.checkInputs();
  34157. // Inertia
  34158. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  34159. if (this.getScene().useRightHandedSystem) {
  34160. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  34161. }
  34162. else {
  34163. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  34164. }
  34165. this.beta += this.inertialBetaOffset;
  34166. this.radius -= this.inertialRadiusOffset;
  34167. this.inertialAlphaOffset *= this.inertia;
  34168. this.inertialBetaOffset *= this.inertia;
  34169. this.inertialRadiusOffset *= this.inertia;
  34170. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  34171. this.inertialAlphaOffset = 0;
  34172. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  34173. this.inertialBetaOffset = 0;
  34174. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  34175. this.inertialRadiusOffset = 0;
  34176. }
  34177. // Panning inertia
  34178. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  34179. if (!this._localDirection) {
  34180. this._localDirection = BABYLON.Vector3.Zero();
  34181. this._transformedDirection = BABYLON.Vector3.Zero();
  34182. }
  34183. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  34184. this._localDirection.multiplyInPlace(this.panningAxis);
  34185. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  34186. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  34187. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  34188. if (!this.panningAxis.y) {
  34189. this._transformedDirection.y = 0;
  34190. }
  34191. if (!this._targetHost) {
  34192. this._target.addInPlace(this._transformedDirection);
  34193. }
  34194. this.inertialPanningX *= this.panningInertia;
  34195. this.inertialPanningY *= this.panningInertia;
  34196. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  34197. this.inertialPanningX = 0;
  34198. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  34199. this.inertialPanningY = 0;
  34200. }
  34201. // Limits
  34202. this._checkLimits();
  34203. _super.prototype._checkInputs.call(this);
  34204. };
  34205. ArcRotateCamera.prototype._checkLimits = function () {
  34206. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  34207. if (this.allowUpsideDown && this.beta > Math.PI) {
  34208. this.beta = this.beta - (2 * Math.PI);
  34209. }
  34210. }
  34211. else {
  34212. if (this.beta < this.lowerBetaLimit) {
  34213. this.beta = this.lowerBetaLimit;
  34214. }
  34215. }
  34216. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  34217. if (this.allowUpsideDown && this.beta < -Math.PI) {
  34218. this.beta = this.beta + (2 * Math.PI);
  34219. }
  34220. }
  34221. else {
  34222. if (this.beta > this.upperBetaLimit) {
  34223. this.beta = this.upperBetaLimit;
  34224. }
  34225. }
  34226. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  34227. this.alpha = this.lowerAlphaLimit;
  34228. }
  34229. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  34230. this.alpha = this.upperAlphaLimit;
  34231. }
  34232. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  34233. this.radius = this.lowerRadiusLimit;
  34234. }
  34235. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  34236. this.radius = this.upperRadiusLimit;
  34237. }
  34238. };
  34239. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  34240. var radiusv3 = this.position.subtract(this._getTargetPosition());
  34241. this.radius = radiusv3.length();
  34242. // Alpha
  34243. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  34244. if (radiusv3.z < 0) {
  34245. this.alpha = 2 * Math.PI - this.alpha;
  34246. }
  34247. // Beta
  34248. this.beta = Math.acos(radiusv3.y / this.radius);
  34249. this._checkLimits();
  34250. };
  34251. ArcRotateCamera.prototype.setPosition = function (position) {
  34252. if (this.position.equals(position)) {
  34253. return;
  34254. }
  34255. this.position.copyFrom(position);
  34256. this.rebuildAnglesAndRadius();
  34257. };
  34258. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  34259. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  34260. if (allowSamePosition === void 0) { allowSamePosition = false; }
  34261. if (target.getBoundingInfo) {
  34262. if (toBoundingCenter) {
  34263. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  34264. }
  34265. else {
  34266. this._targetBoundingCenter = null;
  34267. }
  34268. this._targetHost = target;
  34269. this._target = this._getTargetPosition();
  34270. }
  34271. else {
  34272. var newTarget = target;
  34273. var currentTarget = this._getTargetPosition();
  34274. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  34275. return;
  34276. }
  34277. this._target = newTarget;
  34278. this._targetBoundingCenter = null;
  34279. }
  34280. this.rebuildAnglesAndRadius();
  34281. };
  34282. ArcRotateCamera.prototype._getViewMatrix = function () {
  34283. // Compute
  34284. var cosa = Math.cos(this.alpha);
  34285. var sina = Math.sin(this.alpha);
  34286. var cosb = Math.cos(this.beta);
  34287. var sinb = Math.sin(this.beta);
  34288. if (sinb === 0) {
  34289. sinb = 0.0001;
  34290. }
  34291. var target = this._getTargetPosition();
  34292. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  34293. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  34294. if (!this._collider) {
  34295. this._collider = new BABYLON.Collider();
  34296. }
  34297. this._collider.radius = this.collisionRadius;
  34298. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  34299. this._collisionTriggered = true;
  34300. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34301. }
  34302. else {
  34303. this.position.copyFrom(this._newPosition);
  34304. var up = this.upVector;
  34305. if (this.allowUpsideDown && sinb < 0) {
  34306. up = up.clone();
  34307. up = up.negate();
  34308. }
  34309. if (this.getScene().useRightHandedSystem) {
  34310. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  34311. }
  34312. else {
  34313. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  34314. }
  34315. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  34316. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  34317. }
  34318. this._currentTarget = target;
  34319. return this._viewMatrix;
  34320. };
  34321. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  34322. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  34323. meshes = meshes || this.getScene().meshes;
  34324. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  34325. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  34326. this.radius = distance * this.zoomOnFactor;
  34327. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  34328. };
  34329. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  34330. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  34331. var meshesOrMinMaxVector;
  34332. var distance;
  34333. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  34334. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  34335. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  34336. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  34337. }
  34338. else {
  34339. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  34340. distance = meshesOrMinMaxVectorAndDistance.distance;
  34341. }
  34342. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  34343. if (!doNotUpdateMaxZ) {
  34344. this.maxZ = distance * 2;
  34345. }
  34346. };
  34347. /**
  34348. * @override
  34349. * Override Camera.createRigCamera
  34350. */
  34351. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34352. var alphaShift;
  34353. switch (this.cameraRigMode) {
  34354. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34355. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34356. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34357. case BABYLON.Camera.RIG_MODE_VR:
  34358. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  34359. break;
  34360. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34361. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  34362. break;
  34363. }
  34364. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  34365. rigCam._cameraRigParams = {};
  34366. return rigCam;
  34367. };
  34368. /**
  34369. * @override
  34370. * Override Camera._updateRigCameras
  34371. */
  34372. ArcRotateCamera.prototype._updateRigCameras = function () {
  34373. var camLeft = this._rigCameras[0];
  34374. var camRight = this._rigCameras[1];
  34375. camLeft.beta = camRight.beta = this.beta;
  34376. camLeft.radius = camRight.radius = this.radius;
  34377. switch (this.cameraRigMode) {
  34378. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34379. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34380. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34381. case BABYLON.Camera.RIG_MODE_VR:
  34382. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  34383. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  34384. break;
  34385. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34386. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  34387. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  34388. break;
  34389. }
  34390. _super.prototype._updateRigCameras.call(this);
  34391. };
  34392. ArcRotateCamera.prototype.dispose = function () {
  34393. this.inputs.clear();
  34394. _super.prototype.dispose.call(this);
  34395. };
  34396. ArcRotateCamera.prototype.getClassName = function () {
  34397. return "ArcRotateCamera";
  34398. };
  34399. return ArcRotateCamera;
  34400. }(BABYLON.TargetCamera));
  34401. __decorate([
  34402. BABYLON.serialize()
  34403. ], ArcRotateCamera.prototype, "alpha", void 0);
  34404. __decorate([
  34405. BABYLON.serialize()
  34406. ], ArcRotateCamera.prototype, "beta", void 0);
  34407. __decorate([
  34408. BABYLON.serialize()
  34409. ], ArcRotateCamera.prototype, "radius", void 0);
  34410. __decorate([
  34411. BABYLON.serializeAsVector3("target")
  34412. ], ArcRotateCamera.prototype, "_target", void 0);
  34413. __decorate([
  34414. BABYLON.serialize()
  34415. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  34416. __decorate([
  34417. BABYLON.serialize()
  34418. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  34419. __decorate([
  34420. BABYLON.serialize()
  34421. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  34422. __decorate([
  34423. BABYLON.serialize()
  34424. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  34425. __decorate([
  34426. BABYLON.serialize()
  34427. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  34428. __decorate([
  34429. BABYLON.serialize()
  34430. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  34431. __decorate([
  34432. BABYLON.serialize()
  34433. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  34434. __decorate([
  34435. BABYLON.serialize()
  34436. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  34437. __decorate([
  34438. BABYLON.serialize()
  34439. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  34440. __decorate([
  34441. BABYLON.serialize()
  34442. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  34443. __decorate([
  34444. BABYLON.serialize()
  34445. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  34446. __decorate([
  34447. BABYLON.serialize()
  34448. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  34449. __decorate([
  34450. BABYLON.serialize()
  34451. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  34452. __decorate([
  34453. BABYLON.serialize()
  34454. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  34455. BABYLON.ArcRotateCamera = ArcRotateCamera;
  34456. })(BABYLON || (BABYLON = {}));
  34457. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  34458. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  34459. var BABYLON;
  34460. (function (BABYLON) {
  34461. var ArcRotateCameraInputsManager = (function (_super) {
  34462. __extends(ArcRotateCameraInputsManager, _super);
  34463. function ArcRotateCameraInputsManager(camera) {
  34464. return _super.call(this, camera) || this;
  34465. }
  34466. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  34467. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  34468. return this;
  34469. };
  34470. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  34471. this.add(new BABYLON.ArcRotateCameraPointersInput());
  34472. return this;
  34473. };
  34474. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  34475. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  34476. return this;
  34477. };
  34478. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  34479. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  34480. return this;
  34481. };
  34482. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  34483. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  34484. return this;
  34485. };
  34486. return ArcRotateCameraInputsManager;
  34487. }(BABYLON.CameraInputsManager));
  34488. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  34489. })(BABYLON || (BABYLON = {}));
  34490. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  34491. var BABYLON;
  34492. (function (BABYLON) {
  34493. var HemisphericLight = (function (_super) {
  34494. __extends(HemisphericLight, _super);
  34495. /**
  34496. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  34497. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  34498. * The HemisphericLight can't cast shadows.
  34499. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34500. */
  34501. function HemisphericLight(name, direction, scene) {
  34502. var _this = _super.call(this, name, scene) || this;
  34503. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  34504. _this.direction = direction || BABYLON.Vector3.Up();
  34505. return _this;
  34506. }
  34507. HemisphericLight.prototype._buildUniformLayout = function () {
  34508. this._uniformBuffer.addUniform("vLightData", 4);
  34509. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34510. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34511. this._uniformBuffer.addUniform("vLightGround", 3);
  34512. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34513. this._uniformBuffer.addUniform("depthValues", 2);
  34514. this._uniformBuffer.create();
  34515. };
  34516. /**
  34517. * Returns the string "HemisphericLight".
  34518. */
  34519. HemisphericLight.prototype.getClassName = function () {
  34520. return "HemisphericLight";
  34521. };
  34522. /**
  34523. * Sets the HemisphericLight direction towards the passed target (Vector3).
  34524. * Returns the updated direction.
  34525. */
  34526. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  34527. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  34528. return this.direction;
  34529. };
  34530. HemisphericLight.prototype.getShadowGenerator = function () {
  34531. return null;
  34532. };
  34533. /**
  34534. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  34535. * Returns the HemisphericLight.
  34536. */
  34537. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  34538. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34539. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  34540. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  34541. return this;
  34542. };
  34543. HemisphericLight.prototype._getWorldMatrix = function () {
  34544. if (!this._worldMatrix) {
  34545. this._worldMatrix = BABYLON.Matrix.Identity();
  34546. }
  34547. return this._worldMatrix;
  34548. };
  34549. /**
  34550. * Returns the integer 3.
  34551. */
  34552. HemisphericLight.prototype.getTypeID = function () {
  34553. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  34554. };
  34555. return HemisphericLight;
  34556. }(BABYLON.Light));
  34557. __decorate([
  34558. BABYLON.serializeAsColor3()
  34559. ], HemisphericLight.prototype, "groundColor", void 0);
  34560. __decorate([
  34561. BABYLON.serializeAsVector3()
  34562. ], HemisphericLight.prototype, "direction", void 0);
  34563. BABYLON.HemisphericLight = HemisphericLight;
  34564. })(BABYLON || (BABYLON = {}));
  34565. //# sourceMappingURL=babylon.hemisphericLight.js.map
  34566. var BABYLON;
  34567. (function (BABYLON) {
  34568. var ShadowLight = (function (_super) {
  34569. __extends(ShadowLight, _super);
  34570. function ShadowLight() {
  34571. var _this = _super !== null && _super.apply(this, arguments) || this;
  34572. _this._needProjectionMatrixCompute = true;
  34573. return _this;
  34574. }
  34575. Object.defineProperty(ShadowLight.prototype, "direction", {
  34576. get: function () {
  34577. return this._direction;
  34578. },
  34579. set: function (value) {
  34580. this._direction = value;
  34581. },
  34582. enumerable: true,
  34583. configurable: true
  34584. });
  34585. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  34586. get: function () {
  34587. return this._shadowMinZ;
  34588. },
  34589. set: function (value) {
  34590. this._shadowMinZ = value;
  34591. this.forceProjectionMatrixCompute();
  34592. },
  34593. enumerable: true,
  34594. configurable: true
  34595. });
  34596. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  34597. get: function () {
  34598. return this._shadowMaxZ;
  34599. },
  34600. set: function (value) {
  34601. this._shadowMaxZ = value;
  34602. this.forceProjectionMatrixCompute();
  34603. },
  34604. enumerable: true,
  34605. configurable: true
  34606. });
  34607. /**
  34608. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  34609. */
  34610. ShadowLight.prototype.computeTransformedInformation = function () {
  34611. if (this.parent && this.parent.getWorldMatrix) {
  34612. if (!this.transformedPosition) {
  34613. this.transformedPosition = BABYLON.Vector3.Zero();
  34614. }
  34615. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  34616. // In case the direction is present.
  34617. if (this.direction) {
  34618. if (!this.transformedDirection) {
  34619. this.transformedDirection = BABYLON.Vector3.Zero();
  34620. }
  34621. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  34622. }
  34623. return true;
  34624. }
  34625. return false;
  34626. };
  34627. /**
  34628. * Return the depth scale used for the shadow map.
  34629. */
  34630. ShadowLight.prototype.getDepthScale = function () {
  34631. return 50.0;
  34632. };
  34633. /**
  34634. * Returns the light direction (Vector3) for any passed face index.
  34635. */
  34636. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  34637. return this.transformedDirection ? this.transformedDirection : this.direction;
  34638. };
  34639. /**
  34640. * Returns the DirectionalLight absolute position in the World.
  34641. */
  34642. ShadowLight.prototype.getAbsolutePosition = function () {
  34643. return this.transformedPosition ? this.transformedPosition : this.position;
  34644. };
  34645. /**
  34646. * Sets the DirectionalLight direction toward the passed target (Vector3).
  34647. * Returns the updated DirectionalLight direction (Vector3).
  34648. */
  34649. ShadowLight.prototype.setDirectionToTarget = function (target) {
  34650. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  34651. return this.direction;
  34652. };
  34653. /**
  34654. * Returns the light rotation (Vector3).
  34655. */
  34656. ShadowLight.prototype.getRotation = function () {
  34657. this.direction.normalize();
  34658. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  34659. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  34660. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  34661. };
  34662. /**
  34663. * Boolean : false by default.
  34664. */
  34665. ShadowLight.prototype.needCube = function () {
  34666. return false;
  34667. };
  34668. /**
  34669. * Specifies wether or not the projection matrix should be recomputed this frame.
  34670. */
  34671. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  34672. return this._needProjectionMatrixCompute;
  34673. };
  34674. /**
  34675. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  34676. */
  34677. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  34678. this._needProjectionMatrixCompute = true;
  34679. };
  34680. /**
  34681. * Get the world matrix of the sahdow lights.
  34682. */
  34683. ShadowLight.prototype._getWorldMatrix = function () {
  34684. if (!this._worldMatrix) {
  34685. this._worldMatrix = BABYLON.Matrix.Identity();
  34686. }
  34687. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  34688. return this._worldMatrix;
  34689. };
  34690. /**
  34691. * Gets the minZ used for shadow according to both the scene and the light.
  34692. * @param activeCamera
  34693. */
  34694. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  34695. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  34696. };
  34697. /**
  34698. * Gets the maxZ used for shadow according to both the scene and the light.
  34699. * @param activeCamera
  34700. */
  34701. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  34702. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  34703. };
  34704. /**
  34705. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  34706. * Returns the light.
  34707. */
  34708. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34709. if (this.customProjectionMatrixBuilder) {
  34710. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  34711. }
  34712. else {
  34713. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34714. }
  34715. return this;
  34716. };
  34717. return ShadowLight;
  34718. }(BABYLON.Light));
  34719. __decorate([
  34720. BABYLON.serializeAsVector3()
  34721. ], ShadowLight.prototype, "position", void 0);
  34722. __decorate([
  34723. BABYLON.serializeAsVector3()
  34724. ], ShadowLight.prototype, "direction", null);
  34725. __decorate([
  34726. BABYLON.serialize()
  34727. ], ShadowLight.prototype, "shadowMinZ", null);
  34728. __decorate([
  34729. BABYLON.serialize()
  34730. ], ShadowLight.prototype, "shadowMaxZ", null);
  34731. BABYLON.ShadowLight = ShadowLight;
  34732. })(BABYLON || (BABYLON = {}));
  34733. //# sourceMappingURL=babylon.shadowLight.js.map
  34734. var BABYLON;
  34735. (function (BABYLON) {
  34736. var PointLight = (function (_super) {
  34737. __extends(PointLight, _super);
  34738. /**
  34739. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  34740. * A PointLight emits the light in every direction.
  34741. * It can cast shadows.
  34742. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  34743. * ```javascript
  34744. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  34745. * ```
  34746. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34747. */
  34748. function PointLight(name, position, scene) {
  34749. var _this = _super.call(this, name, scene) || this;
  34750. _this._shadowAngle = Math.PI / 2;
  34751. _this.position = position;
  34752. return _this;
  34753. }
  34754. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  34755. /**
  34756. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34757. * This specifies what angle the shadow will use to be created.
  34758. *
  34759. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  34760. */
  34761. get: function () {
  34762. return this._shadowAngle;
  34763. },
  34764. /**
  34765. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34766. * This specifies what angle the shadow will use to be created.
  34767. *
  34768. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  34769. */
  34770. set: function (value) {
  34771. this._shadowAngle = value;
  34772. this.forceProjectionMatrixCompute();
  34773. },
  34774. enumerable: true,
  34775. configurable: true
  34776. });
  34777. Object.defineProperty(PointLight.prototype, "direction", {
  34778. get: function () {
  34779. return this._direction;
  34780. },
  34781. /**
  34782. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34783. */
  34784. set: function (value) {
  34785. var previousNeedCube = this.needCube();
  34786. this._direction = value;
  34787. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  34788. this._shadowGenerator.recreateShadowMap();
  34789. }
  34790. },
  34791. enumerable: true,
  34792. configurable: true
  34793. });
  34794. /**
  34795. * Returns the string "PointLight"
  34796. */
  34797. PointLight.prototype.getClassName = function () {
  34798. return "PointLight";
  34799. };
  34800. /**
  34801. * Returns the integer 0.
  34802. */
  34803. PointLight.prototype.getTypeID = function () {
  34804. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  34805. };
  34806. /**
  34807. * Specifies wether or not the shadowmap should be a cube texture.
  34808. */
  34809. PointLight.prototype.needCube = function () {
  34810. return !this.direction;
  34811. };
  34812. /**
  34813. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  34814. */
  34815. PointLight.prototype.getShadowDirection = function (faceIndex) {
  34816. if (this.direction) {
  34817. return _super.prototype.getShadowDirection.call(this, faceIndex);
  34818. }
  34819. else {
  34820. switch (faceIndex) {
  34821. case 0:
  34822. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  34823. case 1:
  34824. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  34825. case 2:
  34826. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  34827. case 3:
  34828. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  34829. case 4:
  34830. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  34831. case 5:
  34832. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  34833. }
  34834. }
  34835. return BABYLON.Vector3.Zero();
  34836. };
  34837. /**
  34838. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  34839. * - fov = PI / 2
  34840. * - aspect ratio : 1.0
  34841. * - z-near and far equal to the active camera minZ and maxZ.
  34842. * Returns the PointLight.
  34843. */
  34844. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34845. var activeCamera = this.getScene().activeCamera;
  34846. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34847. };
  34848. PointLight.prototype._buildUniformLayout = function () {
  34849. this._uniformBuffer.addUniform("vLightData", 4);
  34850. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34851. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34852. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34853. this._uniformBuffer.addUniform("depthValues", 2);
  34854. this._uniformBuffer.create();
  34855. };
  34856. /**
  34857. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  34858. * Returns the PointLight.
  34859. */
  34860. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  34861. if (this.computeTransformedInformation()) {
  34862. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  34863. return this;
  34864. }
  34865. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  34866. return this;
  34867. };
  34868. return PointLight;
  34869. }(BABYLON.ShadowLight));
  34870. __decorate([
  34871. BABYLON.serialize()
  34872. ], PointLight.prototype, "shadowAngle", null);
  34873. BABYLON.PointLight = PointLight;
  34874. })(BABYLON || (BABYLON = {}));
  34875. //# sourceMappingURL=babylon.pointLight.js.map
  34876. /// <reference path="babylon.light.ts" />
  34877. var BABYLON;
  34878. (function (BABYLON) {
  34879. var DirectionalLight = (function (_super) {
  34880. __extends(DirectionalLight, _super);
  34881. /**
  34882. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  34883. * The directional light is emitted from everywhere in the given direction.
  34884. * It can cast shawdows.
  34885. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34886. */
  34887. function DirectionalLight(name, direction, scene) {
  34888. var _this = _super.call(this, name, scene) || this;
  34889. _this._shadowFrustumSize = 0;
  34890. _this._shadowOrthoScale = 0.5;
  34891. _this.autoUpdateExtends = true;
  34892. // Cache
  34893. _this._orthoLeft = Number.MAX_VALUE;
  34894. _this._orthoRight = Number.MIN_VALUE;
  34895. _this._orthoTop = Number.MIN_VALUE;
  34896. _this._orthoBottom = Number.MAX_VALUE;
  34897. _this.position = direction.scale(-1.0);
  34898. _this.direction = direction;
  34899. return _this;
  34900. }
  34901. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  34902. /**
  34903. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  34904. */
  34905. get: function () {
  34906. return this._shadowFrustumSize;
  34907. },
  34908. /**
  34909. * Specifies a fix frustum size for the shadow generation.
  34910. */
  34911. set: function (value) {
  34912. this._shadowFrustumSize = value;
  34913. this.forceProjectionMatrixCompute();
  34914. },
  34915. enumerable: true,
  34916. configurable: true
  34917. });
  34918. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  34919. get: function () {
  34920. return this._shadowOrthoScale;
  34921. },
  34922. set: function (value) {
  34923. this._shadowOrthoScale = value;
  34924. this.forceProjectionMatrixCompute();
  34925. },
  34926. enumerable: true,
  34927. configurable: true
  34928. });
  34929. /**
  34930. * Returns the string "DirectionalLight".
  34931. */
  34932. DirectionalLight.prototype.getClassName = function () {
  34933. return "DirectionalLight";
  34934. };
  34935. /**
  34936. * Returns the integer 1.
  34937. */
  34938. DirectionalLight.prototype.getTypeID = function () {
  34939. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  34940. };
  34941. /**
  34942. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  34943. * Returns the DirectionalLight Shadow projection matrix.
  34944. */
  34945. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34946. if (this.shadowFrustumSize > 0) {
  34947. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  34948. }
  34949. else {
  34950. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34951. }
  34952. };
  34953. /**
  34954. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  34955. * Returns the DirectionalLight Shadow projection matrix.
  34956. */
  34957. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  34958. var activeCamera = this.getScene().activeCamera;
  34959. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  34960. };
  34961. /**
  34962. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  34963. * Returns the DirectionalLight Shadow projection matrix.
  34964. */
  34965. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34966. var activeCamera = this.getScene().activeCamera;
  34967. // Check extends
  34968. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  34969. var tempVector3 = BABYLON.Vector3.Zero();
  34970. this._orthoLeft = Number.MAX_VALUE;
  34971. this._orthoRight = Number.MIN_VALUE;
  34972. this._orthoTop = Number.MIN_VALUE;
  34973. this._orthoBottom = Number.MAX_VALUE;
  34974. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  34975. var mesh = renderList[meshIndex];
  34976. if (!mesh) {
  34977. continue;
  34978. }
  34979. var boundingInfo = mesh.getBoundingInfo();
  34980. if (!boundingInfo) {
  34981. continue;
  34982. }
  34983. var boundingBox = boundingInfo.boundingBox;
  34984. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  34985. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  34986. if (tempVector3.x < this._orthoLeft)
  34987. this._orthoLeft = tempVector3.x;
  34988. if (tempVector3.y < this._orthoBottom)
  34989. this._orthoBottom = tempVector3.y;
  34990. if (tempVector3.x > this._orthoRight)
  34991. this._orthoRight = tempVector3.x;
  34992. if (tempVector3.y > this._orthoTop)
  34993. this._orthoTop = tempVector3.y;
  34994. }
  34995. }
  34996. }
  34997. var xOffset = this._orthoRight - this._orthoLeft;
  34998. var yOffset = this._orthoTop - this._orthoBottom;
  34999. 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);
  35000. };
  35001. DirectionalLight.prototype._buildUniformLayout = function () {
  35002. this._uniformBuffer.addUniform("vLightData", 4);
  35003. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35004. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35005. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35006. this._uniformBuffer.addUniform("depthValues", 2);
  35007. this._uniformBuffer.create();
  35008. };
  35009. /**
  35010. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  35011. * Returns the DirectionalLight.
  35012. */
  35013. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  35014. if (this.computeTransformedInformation()) {
  35015. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  35016. return this;
  35017. }
  35018. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  35019. return this;
  35020. };
  35021. /**
  35022. * Gets the minZ used for shadow according to both the scene and the light.
  35023. *
  35024. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  35025. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  35026. * @param activeCamera
  35027. */
  35028. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  35029. return 1;
  35030. };
  35031. /**
  35032. * Gets the maxZ used for shadow according to both the scene and the light.
  35033. *
  35034. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  35035. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  35036. * @param activeCamera
  35037. */
  35038. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  35039. return 1;
  35040. };
  35041. return DirectionalLight;
  35042. }(BABYLON.ShadowLight));
  35043. __decorate([
  35044. BABYLON.serialize()
  35045. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  35046. __decorate([
  35047. BABYLON.serialize()
  35048. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  35049. __decorate([
  35050. BABYLON.serialize()
  35051. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  35052. BABYLON.DirectionalLight = DirectionalLight;
  35053. })(BABYLON || (BABYLON = {}));
  35054. //# sourceMappingURL=babylon.directionalLight.js.map
  35055. var BABYLON;
  35056. (function (BABYLON) {
  35057. var SpotLight = (function (_super) {
  35058. __extends(SpotLight, _super);
  35059. /**
  35060. * Creates a SpotLight object in the scene with the passed parameters :
  35061. * - `position` (Vector3) is the initial SpotLight position,
  35062. * - `direction` (Vector3) is the initial SpotLight direction,
  35063. * - `angle` (float, in radians) is the spot light cone angle,
  35064. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  35065. * A spot light is a simply light oriented cone.
  35066. * It can cast shadows.
  35067. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35068. */
  35069. function SpotLight(name, position, direction, angle, exponent, scene) {
  35070. var _this = _super.call(this, name, scene) || this;
  35071. _this.position = position;
  35072. _this.direction = direction;
  35073. _this.angle = angle;
  35074. _this.exponent = exponent;
  35075. return _this;
  35076. }
  35077. Object.defineProperty(SpotLight.prototype, "angle", {
  35078. get: function () {
  35079. return this._angle;
  35080. },
  35081. set: function (value) {
  35082. this._angle = value;
  35083. this.forceProjectionMatrixCompute();
  35084. },
  35085. enumerable: true,
  35086. configurable: true
  35087. });
  35088. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  35089. get: function () {
  35090. return this._shadowAngleScale;
  35091. },
  35092. /**
  35093. * Allows scaling the angle of the light for shadow generation only.
  35094. */
  35095. set: function (value) {
  35096. this._shadowAngleScale = value;
  35097. this.forceProjectionMatrixCompute();
  35098. },
  35099. enumerable: true,
  35100. configurable: true
  35101. });
  35102. /**
  35103. * Returns the string "SpotLight".
  35104. */
  35105. SpotLight.prototype.getClassName = function () {
  35106. return "SpotLight";
  35107. };
  35108. /**
  35109. * Returns the integer 2.
  35110. */
  35111. SpotLight.prototype.getTypeID = function () {
  35112. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  35113. };
  35114. /**
  35115. * 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.
  35116. * Returns the SpotLight.
  35117. */
  35118. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35119. var activeCamera = this.getScene().activeCamera;
  35120. this._shadowAngleScale = this._shadowAngleScale || 1;
  35121. var angle = this._shadowAngleScale * this._angle;
  35122. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  35123. };
  35124. SpotLight.prototype._buildUniformLayout = function () {
  35125. this._uniformBuffer.addUniform("vLightData", 4);
  35126. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35127. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35128. this._uniformBuffer.addUniform("vLightDirection", 3);
  35129. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35130. this._uniformBuffer.addUniform("depthValues", 2);
  35131. this._uniformBuffer.create();
  35132. };
  35133. /**
  35134. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  35135. * Return the SpotLight.
  35136. */
  35137. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  35138. var normalizeDirection;
  35139. if (this.computeTransformedInformation()) {
  35140. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  35141. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  35142. }
  35143. else {
  35144. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  35145. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  35146. }
  35147. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  35148. return this;
  35149. };
  35150. return SpotLight;
  35151. }(BABYLON.ShadowLight));
  35152. __decorate([
  35153. BABYLON.serialize()
  35154. ], SpotLight.prototype, "angle", null);
  35155. __decorate([
  35156. BABYLON.serialize()
  35157. /**
  35158. * Allows scaling the angle of the light for shadow generation only.
  35159. */
  35160. ], SpotLight.prototype, "shadowAngleScale", null);
  35161. __decorate([
  35162. BABYLON.serialize()
  35163. ], SpotLight.prototype, "exponent", void 0);
  35164. BABYLON.SpotLight = SpotLight;
  35165. })(BABYLON || (BABYLON = {}));
  35166. //# sourceMappingURL=babylon.spotLight.js.map
  35167. var BABYLON;
  35168. (function (BABYLON) {
  35169. var AnimationRange = (function () {
  35170. function AnimationRange(name, from, to) {
  35171. this.name = name;
  35172. this.from = from;
  35173. this.to = to;
  35174. }
  35175. AnimationRange.prototype.clone = function () {
  35176. return new AnimationRange(this.name, this.from, this.to);
  35177. };
  35178. return AnimationRange;
  35179. }());
  35180. BABYLON.AnimationRange = AnimationRange;
  35181. /**
  35182. * Composed of a frame, and an action function
  35183. */
  35184. var AnimationEvent = (function () {
  35185. function AnimationEvent(frame, action, onlyOnce) {
  35186. this.frame = frame;
  35187. this.action = action;
  35188. this.onlyOnce = onlyOnce;
  35189. this.isDone = false;
  35190. }
  35191. return AnimationEvent;
  35192. }());
  35193. BABYLON.AnimationEvent = AnimationEvent;
  35194. var PathCursor = (function () {
  35195. function PathCursor(path) {
  35196. this.path = path;
  35197. this._onchange = new Array();
  35198. this.value = 0;
  35199. this.animations = new Array();
  35200. }
  35201. PathCursor.prototype.getPoint = function () {
  35202. var point = this.path.getPointAtLengthPosition(this.value);
  35203. return new BABYLON.Vector3(point.x, 0, point.y);
  35204. };
  35205. PathCursor.prototype.moveAhead = function (step) {
  35206. if (step === void 0) { step = 0.002; }
  35207. this.move(step);
  35208. return this;
  35209. };
  35210. PathCursor.prototype.moveBack = function (step) {
  35211. if (step === void 0) { step = 0.002; }
  35212. this.move(-step);
  35213. return this;
  35214. };
  35215. PathCursor.prototype.move = function (step) {
  35216. if (Math.abs(step) > 1) {
  35217. throw "step size should be less than 1.";
  35218. }
  35219. this.value += step;
  35220. this.ensureLimits();
  35221. this.raiseOnChange();
  35222. return this;
  35223. };
  35224. PathCursor.prototype.ensureLimits = function () {
  35225. while (this.value > 1) {
  35226. this.value -= 1;
  35227. }
  35228. while (this.value < 0) {
  35229. this.value += 1;
  35230. }
  35231. return this;
  35232. };
  35233. // used by animation engine
  35234. PathCursor.prototype.markAsDirty = function (propertyName) {
  35235. this.ensureLimits();
  35236. this.raiseOnChange();
  35237. return this;
  35238. };
  35239. PathCursor.prototype.raiseOnChange = function () {
  35240. var _this = this;
  35241. this._onchange.forEach(function (f) { return f(_this); });
  35242. return this;
  35243. };
  35244. PathCursor.prototype.onchange = function (f) {
  35245. this._onchange.push(f);
  35246. return this;
  35247. };
  35248. return PathCursor;
  35249. }());
  35250. BABYLON.PathCursor = PathCursor;
  35251. var Animation = (function () {
  35252. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  35253. this.name = name;
  35254. this.targetProperty = targetProperty;
  35255. this.framePerSecond = framePerSecond;
  35256. this.dataType = dataType;
  35257. this.loopMode = loopMode;
  35258. this.enableBlending = enableBlending;
  35259. this._offsetsCache = {};
  35260. this._highLimitsCache = {};
  35261. this._stopped = false;
  35262. this._blendingFactor = 0;
  35263. // The set of event that will be linked to this animation
  35264. this._events = new Array();
  35265. this.allowMatricesInterpolation = false;
  35266. this.blendingSpeed = 0.01;
  35267. this._ranges = {};
  35268. this.targetPropertyPath = targetProperty.split(".");
  35269. this.dataType = dataType;
  35270. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  35271. }
  35272. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  35273. var dataType = undefined;
  35274. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  35275. dataType = Animation.ANIMATIONTYPE_FLOAT;
  35276. }
  35277. else if (from instanceof BABYLON.Quaternion) {
  35278. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  35279. }
  35280. else if (from instanceof BABYLON.Vector3) {
  35281. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  35282. }
  35283. else if (from instanceof BABYLON.Vector2) {
  35284. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  35285. }
  35286. else if (from instanceof BABYLON.Color3) {
  35287. dataType = Animation.ANIMATIONTYPE_COLOR3;
  35288. }
  35289. else if (from instanceof BABYLON.Size) {
  35290. dataType = Animation.ANIMATIONTYPE_SIZE;
  35291. }
  35292. if (dataType == undefined) {
  35293. return null;
  35294. }
  35295. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  35296. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  35297. animation.setKeys(keys);
  35298. if (easingFunction !== undefined) {
  35299. animation.setEasingFunction(easingFunction);
  35300. }
  35301. return animation;
  35302. };
  35303. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  35304. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  35305. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  35306. };
  35307. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  35308. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  35309. node.animations.push(animation);
  35310. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  35311. };
  35312. // Methods
  35313. /**
  35314. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  35315. */
  35316. Animation.prototype.toString = function (fullDetails) {
  35317. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  35318. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  35319. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  35320. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  35321. if (fullDetails) {
  35322. ret += ", Ranges: {";
  35323. var first = true;
  35324. for (var name in this._ranges) {
  35325. if (first) {
  35326. ret += ", ";
  35327. first = false;
  35328. }
  35329. ret += name;
  35330. }
  35331. ret += "}";
  35332. }
  35333. return ret;
  35334. };
  35335. /**
  35336. * Add an event to this animation.
  35337. */
  35338. Animation.prototype.addEvent = function (event) {
  35339. this._events.push(event);
  35340. };
  35341. /**
  35342. * Remove all events found at the given frame
  35343. * @param frame
  35344. */
  35345. Animation.prototype.removeEvents = function (frame) {
  35346. for (var index = 0; index < this._events.length; index++) {
  35347. if (this._events[index].frame === frame) {
  35348. this._events.splice(index, 1);
  35349. index--;
  35350. }
  35351. }
  35352. };
  35353. Animation.prototype.createRange = function (name, from, to) {
  35354. // check name not already in use; could happen for bones after serialized
  35355. if (!this._ranges[name]) {
  35356. this._ranges[name] = new AnimationRange(name, from, to);
  35357. }
  35358. };
  35359. Animation.prototype.deleteRange = function (name, deleteFrames) {
  35360. if (deleteFrames === void 0) { deleteFrames = true; }
  35361. if (this._ranges[name]) {
  35362. if (deleteFrames) {
  35363. var from = this._ranges[name].from;
  35364. var to = this._ranges[name].to;
  35365. // this loop MUST go high to low for multiple splices to work
  35366. for (var key = this._keys.length - 1; key >= 0; key--) {
  35367. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  35368. this._keys.splice(key, 1);
  35369. }
  35370. }
  35371. }
  35372. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  35373. }
  35374. };
  35375. Animation.prototype.getRange = function (name) {
  35376. return this._ranges[name];
  35377. };
  35378. Animation.prototype.reset = function () {
  35379. this._offsetsCache = {};
  35380. this._highLimitsCache = {};
  35381. this.currentFrame = 0;
  35382. this._blendingFactor = 0;
  35383. this._originalBlendValue = null;
  35384. };
  35385. Animation.prototype.isStopped = function () {
  35386. return this._stopped;
  35387. };
  35388. Animation.prototype.getKeys = function () {
  35389. return this._keys;
  35390. };
  35391. Animation.prototype.getHighestFrame = function () {
  35392. var ret = 0;
  35393. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  35394. if (ret < this._keys[key].frame) {
  35395. ret = this._keys[key].frame;
  35396. }
  35397. }
  35398. return ret;
  35399. };
  35400. Animation.prototype.getEasingFunction = function () {
  35401. return this._easingFunction;
  35402. };
  35403. Animation.prototype.setEasingFunction = function (easingFunction) {
  35404. this._easingFunction = easingFunction;
  35405. };
  35406. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  35407. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  35408. };
  35409. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35410. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  35411. };
  35412. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  35413. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  35414. };
  35415. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35416. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  35417. };
  35418. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  35419. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  35420. };
  35421. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35422. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  35423. };
  35424. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  35425. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  35426. };
  35427. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35428. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  35429. };
  35430. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  35431. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  35432. };
  35433. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  35434. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  35435. };
  35436. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  35437. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  35438. };
  35439. Animation.prototype.clone = function () {
  35440. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  35441. clone.enableBlending = this.enableBlending;
  35442. clone.blendingSpeed = this.blendingSpeed;
  35443. if (this._keys) {
  35444. clone.setKeys(this._keys);
  35445. }
  35446. if (this._ranges) {
  35447. clone._ranges = {};
  35448. for (var name in this._ranges) {
  35449. clone._ranges[name] = this._ranges[name].clone();
  35450. }
  35451. }
  35452. return clone;
  35453. };
  35454. Animation.prototype.setKeys = function (values) {
  35455. this._keys = values.slice(0);
  35456. this._offsetsCache = {};
  35457. this._highLimitsCache = {};
  35458. };
  35459. Animation.prototype._getKeyValue = function (value) {
  35460. if (typeof value === "function") {
  35461. return value();
  35462. }
  35463. return value;
  35464. };
  35465. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  35466. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  35467. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  35468. }
  35469. this.currentFrame = currentFrame;
  35470. // Try to get a hash to find the right key
  35471. 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));
  35472. if (this._keys[startKeyIndex].frame >= currentFrame) {
  35473. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  35474. startKeyIndex--;
  35475. }
  35476. }
  35477. for (var key = startKeyIndex; key < this._keys.length; key++) {
  35478. var endKey = this._keys[key + 1];
  35479. if (endKey.frame >= currentFrame) {
  35480. var startKey = this._keys[key];
  35481. var startValue = this._getKeyValue(startKey.value);
  35482. var endValue = this._getKeyValue(endKey.value);
  35483. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  35484. var frameDelta = endKey.frame - startKey.frame;
  35485. // gradient : percent of currentFrame between the frame inf and the frame sup
  35486. var gradient = (currentFrame - startKey.frame) / frameDelta;
  35487. // check for easingFunction and correction of gradient
  35488. if (this._easingFunction != null) {
  35489. gradient = this._easingFunction.ease(gradient);
  35490. }
  35491. switch (this.dataType) {
  35492. // Float
  35493. case Animation.ANIMATIONTYPE_FLOAT:
  35494. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  35495. switch (loopMode) {
  35496. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35497. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35498. return floatValue;
  35499. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35500. return offsetValue * repeatCount + floatValue;
  35501. }
  35502. break;
  35503. // Quaternion
  35504. case Animation.ANIMATIONTYPE_QUATERNION:
  35505. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  35506. switch (loopMode) {
  35507. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35508. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35509. return quatValue;
  35510. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35511. return quatValue.add(offsetValue.scale(repeatCount));
  35512. }
  35513. return quatValue;
  35514. // Vector3
  35515. case Animation.ANIMATIONTYPE_VECTOR3:
  35516. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  35517. switch (loopMode) {
  35518. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35519. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35520. return vec3Value;
  35521. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35522. return vec3Value.add(offsetValue.scale(repeatCount));
  35523. }
  35524. // Vector2
  35525. case Animation.ANIMATIONTYPE_VECTOR2:
  35526. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  35527. switch (loopMode) {
  35528. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35529. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35530. return vec2Value;
  35531. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35532. return vec2Value.add(offsetValue.scale(repeatCount));
  35533. }
  35534. // Size
  35535. case Animation.ANIMATIONTYPE_SIZE:
  35536. switch (loopMode) {
  35537. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35538. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35539. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  35540. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35541. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  35542. }
  35543. // Color3
  35544. case Animation.ANIMATIONTYPE_COLOR3:
  35545. switch (loopMode) {
  35546. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35547. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35548. return this.color3InterpolateFunction(startValue, endValue, gradient);
  35549. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35550. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  35551. }
  35552. // Matrix
  35553. case Animation.ANIMATIONTYPE_MATRIX:
  35554. switch (loopMode) {
  35555. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35556. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35557. if (this.allowMatricesInterpolation) {
  35558. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  35559. }
  35560. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35561. return startValue;
  35562. }
  35563. default:
  35564. break;
  35565. }
  35566. break;
  35567. }
  35568. }
  35569. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  35570. };
  35571. Animation.prototype.setValue = function (currentValue, blend) {
  35572. if (blend === void 0) { blend = false; }
  35573. // Set value
  35574. var path;
  35575. var destination;
  35576. if (this.targetPropertyPath.length > 1) {
  35577. var property = this._target[this.targetPropertyPath[0]];
  35578. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  35579. property = property[this.targetPropertyPath[index]];
  35580. }
  35581. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  35582. destination = property;
  35583. }
  35584. else {
  35585. path = this.targetPropertyPath[0];
  35586. destination = this._target;
  35587. }
  35588. // Blending
  35589. if (this.enableBlending && this._blendingFactor <= 1.0) {
  35590. if (!this._originalBlendValue) {
  35591. if (destination[path].clone) {
  35592. this._originalBlendValue = destination[path].clone();
  35593. }
  35594. else {
  35595. this._originalBlendValue = destination[path];
  35596. }
  35597. }
  35598. if (this._originalBlendValue.prototype) {
  35599. if (this._originalBlendValue.prototype.Lerp) {
  35600. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  35601. }
  35602. else {
  35603. destination[path] = currentValue;
  35604. }
  35605. }
  35606. else if (this._originalBlendValue.m) {
  35607. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  35608. }
  35609. else {
  35610. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  35611. }
  35612. this._blendingFactor += this.blendingSpeed;
  35613. }
  35614. else {
  35615. destination[path] = currentValue;
  35616. }
  35617. if (this._target.markAsDirty) {
  35618. this._target.markAsDirty(this.targetProperty);
  35619. }
  35620. };
  35621. Animation.prototype.goToFrame = function (frame) {
  35622. if (frame < this._keys[0].frame) {
  35623. frame = this._keys[0].frame;
  35624. }
  35625. else if (frame > this._keys[this._keys.length - 1].frame) {
  35626. frame = this._keys[this._keys.length - 1].frame;
  35627. }
  35628. var currentValue = this._interpolate(frame, 0, this.loopMode);
  35629. this.setValue(currentValue);
  35630. };
  35631. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  35632. if (blend === void 0) { blend = false; }
  35633. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  35634. this._stopped = true;
  35635. return false;
  35636. }
  35637. var returnValue = true;
  35638. // Adding a start key at frame 0 if missing
  35639. if (this._keys[0].frame !== 0) {
  35640. var newKey = { frame: 0, value: this._keys[0].value };
  35641. this._keys.splice(0, 0, newKey);
  35642. }
  35643. // Check limits
  35644. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  35645. from = this._keys[0].frame;
  35646. }
  35647. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  35648. to = this._keys[this._keys.length - 1].frame;
  35649. }
  35650. //to and from cannot be the same key
  35651. if (from === to) {
  35652. from++;
  35653. }
  35654. // Compute ratio
  35655. var range = to - from;
  35656. var offsetValue;
  35657. // ratio represents the frame delta between from and to
  35658. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  35659. var highLimitValue = 0;
  35660. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  35661. returnValue = false;
  35662. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  35663. }
  35664. else {
  35665. // Get max value if required
  35666. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  35667. var keyOffset = to.toString() + from.toString();
  35668. if (!this._offsetsCache[keyOffset]) {
  35669. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  35670. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  35671. switch (this.dataType) {
  35672. // Float
  35673. case Animation.ANIMATIONTYPE_FLOAT:
  35674. this._offsetsCache[keyOffset] = toValue - fromValue;
  35675. break;
  35676. // Quaternion
  35677. case Animation.ANIMATIONTYPE_QUATERNION:
  35678. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  35679. break;
  35680. // Vector3
  35681. case Animation.ANIMATIONTYPE_VECTOR3:
  35682. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  35683. // Vector2
  35684. case Animation.ANIMATIONTYPE_VECTOR2:
  35685. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  35686. // Size
  35687. case Animation.ANIMATIONTYPE_SIZE:
  35688. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  35689. // Color3
  35690. case Animation.ANIMATIONTYPE_COLOR3:
  35691. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  35692. default:
  35693. break;
  35694. }
  35695. this._highLimitsCache[keyOffset] = toValue;
  35696. }
  35697. highLimitValue = this._highLimitsCache[keyOffset];
  35698. offsetValue = this._offsetsCache[keyOffset];
  35699. }
  35700. }
  35701. if (offsetValue === undefined) {
  35702. switch (this.dataType) {
  35703. // Float
  35704. case Animation.ANIMATIONTYPE_FLOAT:
  35705. offsetValue = 0;
  35706. break;
  35707. // Quaternion
  35708. case Animation.ANIMATIONTYPE_QUATERNION:
  35709. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  35710. break;
  35711. // Vector3
  35712. case Animation.ANIMATIONTYPE_VECTOR3:
  35713. offsetValue = BABYLON.Vector3.Zero();
  35714. break;
  35715. // Vector2
  35716. case Animation.ANIMATIONTYPE_VECTOR2:
  35717. offsetValue = BABYLON.Vector2.Zero();
  35718. break;
  35719. // Size
  35720. case Animation.ANIMATIONTYPE_SIZE:
  35721. offsetValue = BABYLON.Size.Zero();
  35722. break;
  35723. // Color3
  35724. case Animation.ANIMATIONTYPE_COLOR3:
  35725. offsetValue = BABYLON.Color3.Black();
  35726. }
  35727. }
  35728. // Compute value
  35729. var repeatCount = (ratio / range) >> 0;
  35730. var currentFrame = returnValue ? from + ratio % range : to;
  35731. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  35732. // Set value
  35733. this.setValue(currentValue);
  35734. // Check events
  35735. for (var index = 0; index < this._events.length; index++) {
  35736. // Make sure current frame has passed event frame and that event frame is within the current range
  35737. // Also, handle both forward and reverse animations
  35738. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  35739. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  35740. var event = this._events[index];
  35741. if (!event.isDone) {
  35742. // If event should be done only once, remove it.
  35743. if (event.onlyOnce) {
  35744. this._events.splice(index, 1);
  35745. index--;
  35746. }
  35747. event.isDone = true;
  35748. event.action();
  35749. } // Don't do anything if the event has already be done.
  35750. }
  35751. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  35752. // reset event, the animation is looping
  35753. this._events[index].isDone = false;
  35754. }
  35755. }
  35756. if (!returnValue) {
  35757. this._stopped = true;
  35758. }
  35759. return returnValue;
  35760. };
  35761. Animation.prototype.serialize = function () {
  35762. var serializationObject = {};
  35763. serializationObject.name = this.name;
  35764. serializationObject.property = this.targetProperty;
  35765. serializationObject.framePerSecond = this.framePerSecond;
  35766. serializationObject.dataType = this.dataType;
  35767. serializationObject.loopBehavior = this.loopMode;
  35768. serializationObject.enableBlending = this.enableBlending;
  35769. serializationObject.blendingSpeed = this.blendingSpeed;
  35770. var dataType = this.dataType;
  35771. serializationObject.keys = [];
  35772. var keys = this.getKeys();
  35773. for (var index = 0; index < keys.length; index++) {
  35774. var animationKey = keys[index];
  35775. var key = {};
  35776. key.frame = animationKey.frame;
  35777. switch (dataType) {
  35778. case Animation.ANIMATIONTYPE_FLOAT:
  35779. key.values = [animationKey.value];
  35780. break;
  35781. case Animation.ANIMATIONTYPE_QUATERNION:
  35782. case Animation.ANIMATIONTYPE_MATRIX:
  35783. case Animation.ANIMATIONTYPE_VECTOR3:
  35784. case Animation.ANIMATIONTYPE_COLOR3:
  35785. key.values = animationKey.value.asArray();
  35786. break;
  35787. }
  35788. serializationObject.keys.push(key);
  35789. }
  35790. serializationObject.ranges = [];
  35791. for (var name in this._ranges) {
  35792. var range = {};
  35793. range.name = name;
  35794. range.from = this._ranges[name].from;
  35795. range.to = this._ranges[name].to;
  35796. serializationObject.ranges.push(range);
  35797. }
  35798. return serializationObject;
  35799. };
  35800. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  35801. get: function () {
  35802. return Animation._ANIMATIONTYPE_FLOAT;
  35803. },
  35804. enumerable: true,
  35805. configurable: true
  35806. });
  35807. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  35808. get: function () {
  35809. return Animation._ANIMATIONTYPE_VECTOR3;
  35810. },
  35811. enumerable: true,
  35812. configurable: true
  35813. });
  35814. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  35815. get: function () {
  35816. return Animation._ANIMATIONTYPE_VECTOR2;
  35817. },
  35818. enumerable: true,
  35819. configurable: true
  35820. });
  35821. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  35822. get: function () {
  35823. return Animation._ANIMATIONTYPE_SIZE;
  35824. },
  35825. enumerable: true,
  35826. configurable: true
  35827. });
  35828. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  35829. get: function () {
  35830. return Animation._ANIMATIONTYPE_QUATERNION;
  35831. },
  35832. enumerable: true,
  35833. configurable: true
  35834. });
  35835. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  35836. get: function () {
  35837. return Animation._ANIMATIONTYPE_MATRIX;
  35838. },
  35839. enumerable: true,
  35840. configurable: true
  35841. });
  35842. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  35843. get: function () {
  35844. return Animation._ANIMATIONTYPE_COLOR3;
  35845. },
  35846. enumerable: true,
  35847. configurable: true
  35848. });
  35849. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  35850. get: function () {
  35851. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  35852. },
  35853. enumerable: true,
  35854. configurable: true
  35855. });
  35856. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  35857. get: function () {
  35858. return Animation._ANIMATIONLOOPMODE_CYCLE;
  35859. },
  35860. enumerable: true,
  35861. configurable: true
  35862. });
  35863. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  35864. get: function () {
  35865. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  35866. },
  35867. enumerable: true,
  35868. configurable: true
  35869. });
  35870. Animation.Parse = function (parsedAnimation) {
  35871. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  35872. var dataType = parsedAnimation.dataType;
  35873. var keys = [];
  35874. var data;
  35875. var index;
  35876. if (parsedAnimation.enableBlending) {
  35877. animation.enableBlending = parsedAnimation.enableBlending;
  35878. }
  35879. if (parsedAnimation.blendingSpeed) {
  35880. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  35881. }
  35882. for (index = 0; index < parsedAnimation.keys.length; index++) {
  35883. var key = parsedAnimation.keys[index];
  35884. switch (dataType) {
  35885. case Animation.ANIMATIONTYPE_FLOAT:
  35886. data = key.values[0];
  35887. break;
  35888. case Animation.ANIMATIONTYPE_QUATERNION:
  35889. data = BABYLON.Quaternion.FromArray(key.values);
  35890. break;
  35891. case Animation.ANIMATIONTYPE_MATRIX:
  35892. data = BABYLON.Matrix.FromArray(key.values);
  35893. break;
  35894. case Animation.ANIMATIONTYPE_COLOR3:
  35895. data = BABYLON.Color3.FromArray(key.values);
  35896. break;
  35897. case Animation.ANIMATIONTYPE_VECTOR3:
  35898. default:
  35899. data = BABYLON.Vector3.FromArray(key.values);
  35900. break;
  35901. }
  35902. keys.push({
  35903. frame: key.frame,
  35904. value: data
  35905. });
  35906. }
  35907. animation.setKeys(keys);
  35908. if (parsedAnimation.ranges) {
  35909. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  35910. data = parsedAnimation.ranges[index];
  35911. animation.createRange(data.name, data.from, data.to);
  35912. }
  35913. }
  35914. return animation;
  35915. };
  35916. Animation.AppendSerializedAnimations = function (source, destination) {
  35917. if (source.animations) {
  35918. destination.animations = [];
  35919. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  35920. var animation = source.animations[animationIndex];
  35921. destination.animations.push(animation.serialize());
  35922. }
  35923. }
  35924. };
  35925. return Animation;
  35926. }());
  35927. // Statics
  35928. Animation._ANIMATIONTYPE_FLOAT = 0;
  35929. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  35930. Animation._ANIMATIONTYPE_QUATERNION = 2;
  35931. Animation._ANIMATIONTYPE_MATRIX = 3;
  35932. Animation._ANIMATIONTYPE_COLOR3 = 4;
  35933. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  35934. Animation._ANIMATIONTYPE_SIZE = 6;
  35935. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  35936. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  35937. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  35938. BABYLON.Animation = Animation;
  35939. })(BABYLON || (BABYLON = {}));
  35940. //# sourceMappingURL=babylon.animation.js.map
  35941. var BABYLON;
  35942. (function (BABYLON) {
  35943. var Animatable = (function () {
  35944. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  35945. if (fromFrame === void 0) { fromFrame = 0; }
  35946. if (toFrame === void 0) { toFrame = 100; }
  35947. if (loopAnimation === void 0) { loopAnimation = false; }
  35948. if (speedRatio === void 0) { speedRatio = 1.0; }
  35949. this.target = target;
  35950. this.fromFrame = fromFrame;
  35951. this.toFrame = toFrame;
  35952. this.loopAnimation = loopAnimation;
  35953. this.speedRatio = speedRatio;
  35954. this.onAnimationEnd = onAnimationEnd;
  35955. this._localDelayOffset = null;
  35956. this._pausedDelay = null;
  35957. this._animations = new Array();
  35958. this._paused = false;
  35959. this.animationStarted = false;
  35960. if (animations) {
  35961. this.appendAnimations(target, animations);
  35962. }
  35963. this._scene = scene;
  35964. scene._activeAnimatables.push(this);
  35965. }
  35966. // Methods
  35967. Animatable.prototype.getAnimations = function () {
  35968. return this._animations;
  35969. };
  35970. Animatable.prototype.appendAnimations = function (target, animations) {
  35971. for (var index = 0; index < animations.length; index++) {
  35972. var animation = animations[index];
  35973. animation._target = target;
  35974. this._animations.push(animation);
  35975. }
  35976. };
  35977. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  35978. var animations = this._animations;
  35979. for (var index = 0; index < animations.length; index++) {
  35980. if (animations[index].targetProperty === property) {
  35981. return animations[index];
  35982. }
  35983. }
  35984. return null;
  35985. };
  35986. Animatable.prototype.reset = function () {
  35987. var animations = this._animations;
  35988. for (var index = 0; index < animations.length; index++) {
  35989. animations[index].reset();
  35990. }
  35991. this._localDelayOffset = null;
  35992. this._pausedDelay = null;
  35993. };
  35994. Animatable.prototype.enableBlending = function (blendingSpeed) {
  35995. var animations = this._animations;
  35996. for (var index = 0; index < animations.length; index++) {
  35997. animations[index].enableBlending = true;
  35998. animations[index].blendingSpeed = blendingSpeed;
  35999. }
  36000. };
  36001. Animatable.prototype.disableBlending = function () {
  36002. var animations = this._animations;
  36003. for (var index = 0; index < animations.length; index++) {
  36004. animations[index].enableBlending = false;
  36005. }
  36006. };
  36007. Animatable.prototype.goToFrame = function (frame) {
  36008. var animations = this._animations;
  36009. if (animations[0]) {
  36010. var fps = animations[0].framePerSecond;
  36011. var currentFrame = animations[0].currentFrame;
  36012. var adjustTime = frame - currentFrame;
  36013. var delay = adjustTime * 1000 / fps;
  36014. this._localDelayOffset -= delay;
  36015. }
  36016. for (var index = 0; index < animations.length; index++) {
  36017. animations[index].goToFrame(frame);
  36018. }
  36019. };
  36020. Animatable.prototype.pause = function () {
  36021. if (this._paused) {
  36022. return;
  36023. }
  36024. this._paused = true;
  36025. };
  36026. Animatable.prototype.restart = function () {
  36027. this._paused = false;
  36028. };
  36029. Animatable.prototype.stop = function (animationName) {
  36030. if (animationName) {
  36031. var idx = this._scene._activeAnimatables.indexOf(this);
  36032. if (idx > -1) {
  36033. var animations = this._animations;
  36034. for (var index = animations.length - 1; index >= 0; index--) {
  36035. if (typeof animationName === "string" && animations[index].name != animationName) {
  36036. continue;
  36037. }
  36038. animations[index].reset();
  36039. animations.splice(index, 1);
  36040. }
  36041. if (animations.length == 0) {
  36042. this._scene._activeAnimatables.splice(idx, 1);
  36043. if (this.onAnimationEnd) {
  36044. this.onAnimationEnd();
  36045. }
  36046. }
  36047. }
  36048. }
  36049. else {
  36050. var index = this._scene._activeAnimatables.indexOf(this);
  36051. if (index > -1) {
  36052. this._scene._activeAnimatables.splice(index, 1);
  36053. var animations = this._animations;
  36054. for (var index = 0; index < animations.length; index++) {
  36055. animations[index].reset();
  36056. }
  36057. if (this.onAnimationEnd) {
  36058. this.onAnimationEnd();
  36059. }
  36060. }
  36061. }
  36062. };
  36063. Animatable.prototype._animate = function (delay) {
  36064. if (this._paused) {
  36065. this.animationStarted = false;
  36066. if (this._pausedDelay === null) {
  36067. this._pausedDelay = delay;
  36068. }
  36069. return true;
  36070. }
  36071. if (this._localDelayOffset === null) {
  36072. this._localDelayOffset = delay;
  36073. }
  36074. else if (this._pausedDelay !== null) {
  36075. this._localDelayOffset += delay - this._pausedDelay;
  36076. this._pausedDelay = null;
  36077. }
  36078. // Animating
  36079. var running = false;
  36080. var animations = this._animations;
  36081. var index;
  36082. for (index = 0; index < animations.length; index++) {
  36083. var animation = animations[index];
  36084. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  36085. running = running || isRunning;
  36086. }
  36087. this.animationStarted = running;
  36088. if (!running) {
  36089. // Remove from active animatables
  36090. index = this._scene._activeAnimatables.indexOf(this);
  36091. this._scene._activeAnimatables.splice(index, 1);
  36092. }
  36093. if (!running && this.onAnimationEnd) {
  36094. this.onAnimationEnd();
  36095. this.onAnimationEnd = null;
  36096. }
  36097. return running;
  36098. };
  36099. return Animatable;
  36100. }());
  36101. BABYLON.Animatable = Animatable;
  36102. })(BABYLON || (BABYLON = {}));
  36103. //# sourceMappingURL=babylon.animatable.js.map
  36104. var BABYLON;
  36105. (function (BABYLON) {
  36106. var EasingFunction = (function () {
  36107. function EasingFunction() {
  36108. // Properties
  36109. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  36110. }
  36111. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  36112. get: function () {
  36113. return EasingFunction._EASINGMODE_EASEIN;
  36114. },
  36115. enumerable: true,
  36116. configurable: true
  36117. });
  36118. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  36119. get: function () {
  36120. return EasingFunction._EASINGMODE_EASEOUT;
  36121. },
  36122. enumerable: true,
  36123. configurable: true
  36124. });
  36125. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  36126. get: function () {
  36127. return EasingFunction._EASINGMODE_EASEINOUT;
  36128. },
  36129. enumerable: true,
  36130. configurable: true
  36131. });
  36132. EasingFunction.prototype.setEasingMode = function (easingMode) {
  36133. var n = Math.min(Math.max(easingMode, 0), 2);
  36134. this._easingMode = n;
  36135. };
  36136. EasingFunction.prototype.getEasingMode = function () {
  36137. return this._easingMode;
  36138. };
  36139. EasingFunction.prototype.easeInCore = function (gradient) {
  36140. throw new Error('You must implement this method');
  36141. };
  36142. EasingFunction.prototype.ease = function (gradient) {
  36143. switch (this._easingMode) {
  36144. case EasingFunction.EASINGMODE_EASEIN:
  36145. return this.easeInCore(gradient);
  36146. case EasingFunction.EASINGMODE_EASEOUT:
  36147. return (1 - this.easeInCore(1 - gradient));
  36148. }
  36149. if (gradient >= 0.5) {
  36150. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  36151. }
  36152. return (this.easeInCore(gradient * 2) * 0.5);
  36153. };
  36154. return EasingFunction;
  36155. }());
  36156. //Statics
  36157. EasingFunction._EASINGMODE_EASEIN = 0;
  36158. EasingFunction._EASINGMODE_EASEOUT = 1;
  36159. EasingFunction._EASINGMODE_EASEINOUT = 2;
  36160. BABYLON.EasingFunction = EasingFunction;
  36161. var CircleEase = (function (_super) {
  36162. __extends(CircleEase, _super);
  36163. function CircleEase() {
  36164. return _super !== null && _super.apply(this, arguments) || this;
  36165. }
  36166. CircleEase.prototype.easeInCore = function (gradient) {
  36167. gradient = Math.max(0, Math.min(1, gradient));
  36168. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  36169. };
  36170. return CircleEase;
  36171. }(EasingFunction));
  36172. BABYLON.CircleEase = CircleEase;
  36173. var BackEase = (function (_super) {
  36174. __extends(BackEase, _super);
  36175. function BackEase(amplitude) {
  36176. if (amplitude === void 0) { amplitude = 1; }
  36177. var _this = _super.call(this) || this;
  36178. _this.amplitude = amplitude;
  36179. return _this;
  36180. }
  36181. BackEase.prototype.easeInCore = function (gradient) {
  36182. var num = Math.max(0, this.amplitude);
  36183. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  36184. };
  36185. return BackEase;
  36186. }(EasingFunction));
  36187. BABYLON.BackEase = BackEase;
  36188. var BounceEase = (function (_super) {
  36189. __extends(BounceEase, _super);
  36190. function BounceEase(bounces, bounciness) {
  36191. if (bounces === void 0) { bounces = 3; }
  36192. if (bounciness === void 0) { bounciness = 2; }
  36193. var _this = _super.call(this) || this;
  36194. _this.bounces = bounces;
  36195. _this.bounciness = bounciness;
  36196. return _this;
  36197. }
  36198. BounceEase.prototype.easeInCore = function (gradient) {
  36199. var y = Math.max(0.0, this.bounces);
  36200. var bounciness = this.bounciness;
  36201. if (bounciness <= 1.0) {
  36202. bounciness = 1.001;
  36203. }
  36204. var num9 = Math.pow(bounciness, y);
  36205. var num5 = 1.0 - bounciness;
  36206. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  36207. var num15 = gradient * num4;
  36208. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  36209. var num3 = Math.floor(num65);
  36210. var num13 = num3 + 1.0;
  36211. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  36212. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  36213. var num7 = (num8 + num12) * 0.5;
  36214. var num6 = gradient - num7;
  36215. var num2 = num7 - num8;
  36216. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  36217. };
  36218. return BounceEase;
  36219. }(EasingFunction));
  36220. BABYLON.BounceEase = BounceEase;
  36221. var CubicEase = (function (_super) {
  36222. __extends(CubicEase, _super);
  36223. function CubicEase() {
  36224. return _super !== null && _super.apply(this, arguments) || this;
  36225. }
  36226. CubicEase.prototype.easeInCore = function (gradient) {
  36227. return (gradient * gradient * gradient);
  36228. };
  36229. return CubicEase;
  36230. }(EasingFunction));
  36231. BABYLON.CubicEase = CubicEase;
  36232. var ElasticEase = (function (_super) {
  36233. __extends(ElasticEase, _super);
  36234. function ElasticEase(oscillations, springiness) {
  36235. if (oscillations === void 0) { oscillations = 3; }
  36236. if (springiness === void 0) { springiness = 3; }
  36237. var _this = _super.call(this) || this;
  36238. _this.oscillations = oscillations;
  36239. _this.springiness = springiness;
  36240. return _this;
  36241. }
  36242. ElasticEase.prototype.easeInCore = function (gradient) {
  36243. var num2;
  36244. var num3 = Math.max(0.0, this.oscillations);
  36245. var num = Math.max(0.0, this.springiness);
  36246. if (num == 0) {
  36247. num2 = gradient;
  36248. }
  36249. else {
  36250. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  36251. }
  36252. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  36253. };
  36254. return ElasticEase;
  36255. }(EasingFunction));
  36256. BABYLON.ElasticEase = ElasticEase;
  36257. var ExponentialEase = (function (_super) {
  36258. __extends(ExponentialEase, _super);
  36259. function ExponentialEase(exponent) {
  36260. if (exponent === void 0) { exponent = 2; }
  36261. var _this = _super.call(this) || this;
  36262. _this.exponent = exponent;
  36263. return _this;
  36264. }
  36265. ExponentialEase.prototype.easeInCore = function (gradient) {
  36266. if (this.exponent <= 0) {
  36267. return gradient;
  36268. }
  36269. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  36270. };
  36271. return ExponentialEase;
  36272. }(EasingFunction));
  36273. BABYLON.ExponentialEase = ExponentialEase;
  36274. var PowerEase = (function (_super) {
  36275. __extends(PowerEase, _super);
  36276. function PowerEase(power) {
  36277. if (power === void 0) { power = 2; }
  36278. var _this = _super.call(this) || this;
  36279. _this.power = power;
  36280. return _this;
  36281. }
  36282. PowerEase.prototype.easeInCore = function (gradient) {
  36283. var y = Math.max(0.0, this.power);
  36284. return Math.pow(gradient, y);
  36285. };
  36286. return PowerEase;
  36287. }(EasingFunction));
  36288. BABYLON.PowerEase = PowerEase;
  36289. var QuadraticEase = (function (_super) {
  36290. __extends(QuadraticEase, _super);
  36291. function QuadraticEase() {
  36292. return _super !== null && _super.apply(this, arguments) || this;
  36293. }
  36294. QuadraticEase.prototype.easeInCore = function (gradient) {
  36295. return (gradient * gradient);
  36296. };
  36297. return QuadraticEase;
  36298. }(EasingFunction));
  36299. BABYLON.QuadraticEase = QuadraticEase;
  36300. var QuarticEase = (function (_super) {
  36301. __extends(QuarticEase, _super);
  36302. function QuarticEase() {
  36303. return _super !== null && _super.apply(this, arguments) || this;
  36304. }
  36305. QuarticEase.prototype.easeInCore = function (gradient) {
  36306. return (gradient * gradient * gradient * gradient);
  36307. };
  36308. return QuarticEase;
  36309. }(EasingFunction));
  36310. BABYLON.QuarticEase = QuarticEase;
  36311. var QuinticEase = (function (_super) {
  36312. __extends(QuinticEase, _super);
  36313. function QuinticEase() {
  36314. return _super !== null && _super.apply(this, arguments) || this;
  36315. }
  36316. QuinticEase.prototype.easeInCore = function (gradient) {
  36317. return (gradient * gradient * gradient * gradient * gradient);
  36318. };
  36319. return QuinticEase;
  36320. }(EasingFunction));
  36321. BABYLON.QuinticEase = QuinticEase;
  36322. var SineEase = (function (_super) {
  36323. __extends(SineEase, _super);
  36324. function SineEase() {
  36325. return _super !== null && _super.apply(this, arguments) || this;
  36326. }
  36327. SineEase.prototype.easeInCore = function (gradient) {
  36328. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  36329. };
  36330. return SineEase;
  36331. }(EasingFunction));
  36332. BABYLON.SineEase = SineEase;
  36333. var BezierCurveEase = (function (_super) {
  36334. __extends(BezierCurveEase, _super);
  36335. function BezierCurveEase(x1, y1, x2, y2) {
  36336. if (x1 === void 0) { x1 = 0; }
  36337. if (y1 === void 0) { y1 = 0; }
  36338. if (x2 === void 0) { x2 = 1; }
  36339. if (y2 === void 0) { y2 = 1; }
  36340. var _this = _super.call(this) || this;
  36341. _this.x1 = x1;
  36342. _this.y1 = y1;
  36343. _this.x2 = x2;
  36344. _this.y2 = y2;
  36345. return _this;
  36346. }
  36347. BezierCurveEase.prototype.easeInCore = function (gradient) {
  36348. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  36349. };
  36350. return BezierCurveEase;
  36351. }(EasingFunction));
  36352. BABYLON.BezierCurveEase = BezierCurveEase;
  36353. })(BABYLON || (BABYLON = {}));
  36354. //# sourceMappingURL=babylon.easing.js.map
  36355. var BABYLON;
  36356. (function (BABYLON) {
  36357. var Condition = (function () {
  36358. function Condition(actionManager) {
  36359. this._actionManager = actionManager;
  36360. }
  36361. Condition.prototype.isValid = function () {
  36362. return true;
  36363. };
  36364. Condition.prototype._getProperty = function (propertyPath) {
  36365. return this._actionManager._getProperty(propertyPath);
  36366. };
  36367. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  36368. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36369. };
  36370. Condition.prototype.serialize = function () {
  36371. };
  36372. Condition.prototype._serialize = function (serializedCondition) {
  36373. return {
  36374. type: 2,
  36375. children: [],
  36376. name: serializedCondition.name,
  36377. properties: serializedCondition.properties
  36378. };
  36379. };
  36380. return Condition;
  36381. }());
  36382. BABYLON.Condition = Condition;
  36383. var ValueCondition = (function (_super) {
  36384. __extends(ValueCondition, _super);
  36385. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  36386. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  36387. var _this = _super.call(this, actionManager) || this;
  36388. _this.propertyPath = propertyPath;
  36389. _this.value = value;
  36390. _this.operator = operator;
  36391. _this._target = target;
  36392. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  36393. _this._property = _this._getProperty(_this.propertyPath);
  36394. return _this;
  36395. }
  36396. Object.defineProperty(ValueCondition, "IsEqual", {
  36397. get: function () {
  36398. return ValueCondition._IsEqual;
  36399. },
  36400. enumerable: true,
  36401. configurable: true
  36402. });
  36403. Object.defineProperty(ValueCondition, "IsDifferent", {
  36404. get: function () {
  36405. return ValueCondition._IsDifferent;
  36406. },
  36407. enumerable: true,
  36408. configurable: true
  36409. });
  36410. Object.defineProperty(ValueCondition, "IsGreater", {
  36411. get: function () {
  36412. return ValueCondition._IsGreater;
  36413. },
  36414. enumerable: true,
  36415. configurable: true
  36416. });
  36417. Object.defineProperty(ValueCondition, "IsLesser", {
  36418. get: function () {
  36419. return ValueCondition._IsLesser;
  36420. },
  36421. enumerable: true,
  36422. configurable: true
  36423. });
  36424. // Methods
  36425. ValueCondition.prototype.isValid = function () {
  36426. switch (this.operator) {
  36427. case ValueCondition.IsGreater:
  36428. return this._effectiveTarget[this._property] > this.value;
  36429. case ValueCondition.IsLesser:
  36430. return this._effectiveTarget[this._property] < this.value;
  36431. case ValueCondition.IsEqual:
  36432. case ValueCondition.IsDifferent:
  36433. var check;
  36434. if (this.value.equals) {
  36435. check = this.value.equals(this._effectiveTarget[this._property]);
  36436. }
  36437. else {
  36438. check = this.value === this._effectiveTarget[this._property];
  36439. }
  36440. return this.operator === ValueCondition.IsEqual ? check : !check;
  36441. }
  36442. return false;
  36443. };
  36444. ValueCondition.prototype.serialize = function () {
  36445. return this._serialize({
  36446. name: "ValueCondition",
  36447. properties: [
  36448. BABYLON.Action._GetTargetProperty(this._target),
  36449. { name: "propertyPath", value: this.propertyPath },
  36450. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36451. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  36452. ]
  36453. });
  36454. };
  36455. ValueCondition.GetOperatorName = function (operator) {
  36456. switch (operator) {
  36457. case ValueCondition._IsEqual: return "IsEqual";
  36458. case ValueCondition._IsDifferent: return "IsDifferent";
  36459. case ValueCondition._IsGreater: return "IsGreater";
  36460. case ValueCondition._IsLesser: return "IsLesser";
  36461. default: return "";
  36462. }
  36463. };
  36464. return ValueCondition;
  36465. }(Condition));
  36466. // Statics
  36467. ValueCondition._IsEqual = 0;
  36468. ValueCondition._IsDifferent = 1;
  36469. ValueCondition._IsGreater = 2;
  36470. ValueCondition._IsLesser = 3;
  36471. BABYLON.ValueCondition = ValueCondition;
  36472. var PredicateCondition = (function (_super) {
  36473. __extends(PredicateCondition, _super);
  36474. function PredicateCondition(actionManager, predicate) {
  36475. var _this = _super.call(this, actionManager) || this;
  36476. _this.predicate = predicate;
  36477. return _this;
  36478. }
  36479. PredicateCondition.prototype.isValid = function () {
  36480. return this.predicate();
  36481. };
  36482. return PredicateCondition;
  36483. }(Condition));
  36484. BABYLON.PredicateCondition = PredicateCondition;
  36485. var StateCondition = (function (_super) {
  36486. __extends(StateCondition, _super);
  36487. function StateCondition(actionManager, target, value) {
  36488. var _this = _super.call(this, actionManager) || this;
  36489. _this.value = value;
  36490. _this._target = target;
  36491. return _this;
  36492. }
  36493. // Methods
  36494. StateCondition.prototype.isValid = function () {
  36495. return this._target.state === this.value;
  36496. };
  36497. StateCondition.prototype.serialize = function () {
  36498. return this._serialize({
  36499. name: "StateCondition",
  36500. properties: [
  36501. BABYLON.Action._GetTargetProperty(this._target),
  36502. { name: "value", value: this.value }
  36503. ]
  36504. });
  36505. };
  36506. return StateCondition;
  36507. }(Condition));
  36508. BABYLON.StateCondition = StateCondition;
  36509. })(BABYLON || (BABYLON = {}));
  36510. //# sourceMappingURL=babylon.condition.js.map
  36511. var BABYLON;
  36512. (function (BABYLON) {
  36513. var Action = (function () {
  36514. function Action(triggerOptions, condition) {
  36515. this.triggerOptions = triggerOptions;
  36516. if (triggerOptions.parameter) {
  36517. this.trigger = triggerOptions.trigger;
  36518. this._triggerParameter = triggerOptions.parameter;
  36519. }
  36520. else {
  36521. this.trigger = triggerOptions;
  36522. }
  36523. this._nextActiveAction = this;
  36524. this._condition = condition;
  36525. }
  36526. // Methods
  36527. Action.prototype._prepare = function () {
  36528. };
  36529. Action.prototype.getTriggerParameter = function () {
  36530. return this._triggerParameter;
  36531. };
  36532. Action.prototype._executeCurrent = function (evt) {
  36533. if (this._nextActiveAction._condition) {
  36534. var condition = this._nextActiveAction._condition;
  36535. var currentRenderId = this._actionManager.getScene().getRenderId();
  36536. // We cache the current evaluation for the current frame
  36537. if (condition._evaluationId === currentRenderId) {
  36538. if (!condition._currentResult) {
  36539. return;
  36540. }
  36541. }
  36542. else {
  36543. condition._evaluationId = currentRenderId;
  36544. if (!condition.isValid()) {
  36545. condition._currentResult = false;
  36546. return;
  36547. }
  36548. condition._currentResult = true;
  36549. }
  36550. }
  36551. this._nextActiveAction.execute(evt);
  36552. this.skipToNextActiveAction();
  36553. };
  36554. Action.prototype.execute = function (evt) {
  36555. };
  36556. Action.prototype.skipToNextActiveAction = function () {
  36557. if (this._nextActiveAction._child) {
  36558. if (!this._nextActiveAction._child._actionManager) {
  36559. this._nextActiveAction._child._actionManager = this._actionManager;
  36560. }
  36561. this._nextActiveAction = this._nextActiveAction._child;
  36562. }
  36563. else {
  36564. this._nextActiveAction = this;
  36565. }
  36566. };
  36567. Action.prototype.then = function (action) {
  36568. this._child = action;
  36569. action._actionManager = this._actionManager;
  36570. action._prepare();
  36571. return action;
  36572. };
  36573. Action.prototype._getProperty = function (propertyPath) {
  36574. return this._actionManager._getProperty(propertyPath);
  36575. };
  36576. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  36577. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36578. };
  36579. Action.prototype.serialize = function (parent) {
  36580. };
  36581. // Called by BABYLON.Action objects in serialize(...). Internal use
  36582. Action.prototype._serialize = function (serializedAction, parent) {
  36583. var serializationObject = {
  36584. type: 1,
  36585. children: [],
  36586. name: serializedAction.name,
  36587. properties: serializedAction.properties || []
  36588. };
  36589. // Serialize child
  36590. if (this._child) {
  36591. this._child.serialize(serializationObject);
  36592. }
  36593. // Check if "this" has a condition
  36594. if (this._condition) {
  36595. var serializedCondition = this._condition.serialize();
  36596. serializedCondition.children.push(serializationObject);
  36597. if (parent) {
  36598. parent.children.push(serializedCondition);
  36599. }
  36600. return serializedCondition;
  36601. }
  36602. if (parent) {
  36603. parent.children.push(serializationObject);
  36604. }
  36605. return serializationObject;
  36606. };
  36607. return Action;
  36608. }());
  36609. Action._SerializeValueAsString = function (value) {
  36610. if (typeof value === "number") {
  36611. return value.toString();
  36612. }
  36613. if (typeof value === "boolean") {
  36614. return value ? "true" : "false";
  36615. }
  36616. if (value instanceof BABYLON.Vector2) {
  36617. return value.x + ", " + value.y;
  36618. }
  36619. if (value instanceof BABYLON.Vector3) {
  36620. return value.x + ", " + value.y + ", " + value.z;
  36621. }
  36622. if (value instanceof BABYLON.Color3) {
  36623. return value.r + ", " + value.g + ", " + value.b;
  36624. }
  36625. if (value instanceof BABYLON.Color4) {
  36626. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36627. }
  36628. return value; // string
  36629. };
  36630. Action._GetTargetProperty = function (target) {
  36631. return {
  36632. name: "target",
  36633. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36634. : target instanceof BABYLON.Light ? "LightProperties"
  36635. : target instanceof BABYLON.Camera ? "CameraProperties"
  36636. : "SceneProperties",
  36637. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36638. };
  36639. };
  36640. BABYLON.Action = Action;
  36641. })(BABYLON || (BABYLON = {}));
  36642. //# sourceMappingURL=babylon.action.js.map
  36643. var BABYLON;
  36644. (function (BABYLON) {
  36645. /**
  36646. * ActionEvent is the event beint sent when an action is triggered.
  36647. */
  36648. var ActionEvent = (function () {
  36649. /**
  36650. * @constructor
  36651. * @param source The mesh or sprite that triggered the action.
  36652. * @param pointerX The X mouse cursor position at the time of the event
  36653. * @param pointerY The Y mouse cursor position at the time of the event
  36654. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36655. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36656. */
  36657. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36658. this.source = source;
  36659. this.pointerX = pointerX;
  36660. this.pointerY = pointerY;
  36661. this.meshUnderPointer = meshUnderPointer;
  36662. this.sourceEvent = sourceEvent;
  36663. this.additionalData = additionalData;
  36664. }
  36665. /**
  36666. * Helper function to auto-create an ActionEvent from a source mesh.
  36667. * @param source The source mesh that triggered the event
  36668. * @param evt {Event} The original (browser) event
  36669. */
  36670. ActionEvent.CreateNew = function (source, evt, additionalData) {
  36671. var scene = source.getScene();
  36672. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36673. };
  36674. /**
  36675. * Helper function to auto-create an ActionEvent from a source mesh.
  36676. * @param source The source sprite that triggered the event
  36677. * @param scene Scene associated with the sprite
  36678. * @param evt {Event} The original (browser) event
  36679. */
  36680. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  36681. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36682. };
  36683. /**
  36684. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  36685. * @param scene the scene where the event occurred
  36686. * @param evt {Event} The original (browser) event
  36687. */
  36688. ActionEvent.CreateNewFromScene = function (scene, evt) {
  36689. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  36690. };
  36691. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  36692. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  36693. };
  36694. return ActionEvent;
  36695. }());
  36696. BABYLON.ActionEvent = ActionEvent;
  36697. /**
  36698. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  36699. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  36700. */
  36701. var ActionManager = (function () {
  36702. function ActionManager(scene) {
  36703. // Members
  36704. this.actions = new Array();
  36705. this.hoverCursor = '';
  36706. this._scene = scene;
  36707. scene._actionManagers.push(this);
  36708. }
  36709. Object.defineProperty(ActionManager, "NothingTrigger", {
  36710. get: function () {
  36711. return ActionManager._NothingTrigger;
  36712. },
  36713. enumerable: true,
  36714. configurable: true
  36715. });
  36716. Object.defineProperty(ActionManager, "OnPickTrigger", {
  36717. get: function () {
  36718. return ActionManager._OnPickTrigger;
  36719. },
  36720. enumerable: true,
  36721. configurable: true
  36722. });
  36723. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  36724. get: function () {
  36725. return ActionManager._OnLeftPickTrigger;
  36726. },
  36727. enumerable: true,
  36728. configurable: true
  36729. });
  36730. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  36731. get: function () {
  36732. return ActionManager._OnRightPickTrigger;
  36733. },
  36734. enumerable: true,
  36735. configurable: true
  36736. });
  36737. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  36738. get: function () {
  36739. return ActionManager._OnCenterPickTrigger;
  36740. },
  36741. enumerable: true,
  36742. configurable: true
  36743. });
  36744. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  36745. get: function () {
  36746. return ActionManager._OnPickDownTrigger;
  36747. },
  36748. enumerable: true,
  36749. configurable: true
  36750. });
  36751. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  36752. get: function () {
  36753. return ActionManager._OnDoublePickTrigger;
  36754. },
  36755. enumerable: true,
  36756. configurable: true
  36757. });
  36758. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  36759. get: function () {
  36760. return ActionManager._OnPickUpTrigger;
  36761. },
  36762. enumerable: true,
  36763. configurable: true
  36764. });
  36765. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  36766. /// This trigger will only be raised if you also declared a OnPickDown
  36767. get: function () {
  36768. return ActionManager._OnPickOutTrigger;
  36769. },
  36770. enumerable: true,
  36771. configurable: true
  36772. });
  36773. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  36774. get: function () {
  36775. return ActionManager._OnLongPressTrigger;
  36776. },
  36777. enumerable: true,
  36778. configurable: true
  36779. });
  36780. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  36781. get: function () {
  36782. return ActionManager._OnPointerOverTrigger;
  36783. },
  36784. enumerable: true,
  36785. configurable: true
  36786. });
  36787. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36788. get: function () {
  36789. return ActionManager._OnPointerOutTrigger;
  36790. },
  36791. enumerable: true,
  36792. configurable: true
  36793. });
  36794. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36795. get: function () {
  36796. return ActionManager._OnEveryFrameTrigger;
  36797. },
  36798. enumerable: true,
  36799. configurable: true
  36800. });
  36801. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36802. get: function () {
  36803. return ActionManager._OnIntersectionEnterTrigger;
  36804. },
  36805. enumerable: true,
  36806. configurable: true
  36807. });
  36808. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36809. get: function () {
  36810. return ActionManager._OnIntersectionExitTrigger;
  36811. },
  36812. enumerable: true,
  36813. configurable: true
  36814. });
  36815. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36816. get: function () {
  36817. return ActionManager._OnKeyDownTrigger;
  36818. },
  36819. enumerable: true,
  36820. configurable: true
  36821. });
  36822. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36823. get: function () {
  36824. return ActionManager._OnKeyUpTrigger;
  36825. },
  36826. enumerable: true,
  36827. configurable: true
  36828. });
  36829. // Methods
  36830. ActionManager.prototype.dispose = function () {
  36831. var index = this._scene._actionManagers.indexOf(this);
  36832. for (var i = 0; i < this.actions.length; i++) {
  36833. var action = this.actions[i];
  36834. ActionManager.Triggers[action.trigger]--;
  36835. if (ActionManager.Triggers[action.trigger] === 0) {
  36836. delete ActionManager.Triggers[action.trigger];
  36837. }
  36838. }
  36839. if (index > -1) {
  36840. this._scene._actionManagers.splice(index, 1);
  36841. }
  36842. };
  36843. ActionManager.prototype.getScene = function () {
  36844. return this._scene;
  36845. };
  36846. /**
  36847. * Does this action manager handles actions of any of the given triggers
  36848. * @param {number[]} triggers - the triggers to be tested
  36849. * @return {boolean} whether one (or more) of the triggers is handeled
  36850. */
  36851. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36852. for (var index = 0; index < this.actions.length; index++) {
  36853. var action = this.actions[index];
  36854. if (triggers.indexOf(action.trigger) > -1) {
  36855. return true;
  36856. }
  36857. }
  36858. return false;
  36859. };
  36860. /**
  36861. * Does this action manager handles actions of a given trigger
  36862. * @param {number} trigger - the trigger to be tested
  36863. * @return {boolean} whether the trigger is handeled
  36864. */
  36865. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36866. for (var index = 0; index < this.actions.length; index++) {
  36867. var action = this.actions[index];
  36868. if (action.trigger === trigger) {
  36869. return true;
  36870. }
  36871. }
  36872. return false;
  36873. };
  36874. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36875. /**
  36876. * Does this action manager has pointer triggers
  36877. * @return {boolean} whether or not it has pointer triggers
  36878. */
  36879. get: function () {
  36880. for (var index = 0; index < this.actions.length; index++) {
  36881. var action = this.actions[index];
  36882. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36883. return true;
  36884. }
  36885. }
  36886. return false;
  36887. },
  36888. enumerable: true,
  36889. configurable: true
  36890. });
  36891. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36892. /**
  36893. * Does this action manager has pick triggers
  36894. * @return {boolean} whether or not it has pick triggers
  36895. */
  36896. get: function () {
  36897. for (var index = 0; index < this.actions.length; index++) {
  36898. var action = this.actions[index];
  36899. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36900. return true;
  36901. }
  36902. }
  36903. return false;
  36904. },
  36905. enumerable: true,
  36906. configurable: true
  36907. });
  36908. Object.defineProperty(ActionManager, "HasTriggers", {
  36909. /**
  36910. * Does exist one action manager with at least one trigger
  36911. * @return {boolean} whether or not it exists one action manager with one trigger
  36912. **/
  36913. get: function () {
  36914. for (var t in ActionManager.Triggers) {
  36915. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36916. return true;
  36917. }
  36918. }
  36919. return false;
  36920. },
  36921. enumerable: true,
  36922. configurable: true
  36923. });
  36924. Object.defineProperty(ActionManager, "HasPickTriggers", {
  36925. /**
  36926. * Does exist one action manager with at least one pick trigger
  36927. * @return {boolean} whether or not it exists one action manager with one pick trigger
  36928. **/
  36929. get: function () {
  36930. for (var t in ActionManager.Triggers) {
  36931. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36932. var t_int = parseInt(t);
  36933. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  36934. return true;
  36935. }
  36936. }
  36937. }
  36938. return false;
  36939. },
  36940. enumerable: true,
  36941. configurable: true
  36942. });
  36943. /**
  36944. * Does exist one action manager that handles actions of a given trigger
  36945. * @param {number} trigger - the trigger to be tested
  36946. * @return {boolean} whether the trigger is handeled by at least one action manager
  36947. **/
  36948. ActionManager.HasSpecificTrigger = function (trigger) {
  36949. for (var t in ActionManager.Triggers) {
  36950. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36951. var t_int = parseInt(t);
  36952. if (t_int === trigger) {
  36953. return true;
  36954. }
  36955. }
  36956. }
  36957. return false;
  36958. };
  36959. /**
  36960. * Registers an action to this action manager
  36961. * @param {BABYLON.Action} action - the action to be registered
  36962. * @return {BABYLON.Action} the action amended (prepared) after registration
  36963. */
  36964. ActionManager.prototype.registerAction = function (action) {
  36965. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36966. if (this.getScene().actionManager !== this) {
  36967. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36968. return null;
  36969. }
  36970. }
  36971. this.actions.push(action);
  36972. if (ActionManager.Triggers[action.trigger]) {
  36973. ActionManager.Triggers[action.trigger]++;
  36974. }
  36975. else {
  36976. ActionManager.Triggers[action.trigger] = 1;
  36977. }
  36978. action._actionManager = this;
  36979. action._prepare();
  36980. return action;
  36981. };
  36982. /**
  36983. * Process a specific trigger
  36984. * @param {number} trigger - the trigger to process
  36985. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36986. */
  36987. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36988. for (var index = 0; index < this.actions.length; index++) {
  36989. var action = this.actions[index];
  36990. if (action.trigger === trigger) {
  36991. if (trigger === ActionManager.OnKeyUpTrigger
  36992. || trigger === ActionManager.OnKeyDownTrigger) {
  36993. var parameter = action.getTriggerParameter();
  36994. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  36995. if (!parameter.toLowerCase) {
  36996. continue;
  36997. }
  36998. var lowerCase = parameter.toLowerCase();
  36999. if (lowerCase !== evt.sourceEvent.key) {
  37000. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  37001. var actualkey = String.fromCharCode(unicode).toLowerCase();
  37002. if (actualkey !== lowerCase) {
  37003. continue;
  37004. }
  37005. }
  37006. }
  37007. }
  37008. action._executeCurrent(evt);
  37009. }
  37010. }
  37011. };
  37012. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  37013. var properties = propertyPath.split(".");
  37014. for (var index = 0; index < properties.length - 1; index++) {
  37015. target = target[properties[index]];
  37016. }
  37017. return target;
  37018. };
  37019. ActionManager.prototype._getProperty = function (propertyPath) {
  37020. var properties = propertyPath.split(".");
  37021. return properties[properties.length - 1];
  37022. };
  37023. ActionManager.prototype.serialize = function (name) {
  37024. var root = {
  37025. children: [],
  37026. name: name,
  37027. type: 3,
  37028. properties: [] // Empty for root but required
  37029. };
  37030. for (var i = 0; i < this.actions.length; i++) {
  37031. var triggerObject = {
  37032. type: 0,
  37033. children: [],
  37034. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  37035. properties: []
  37036. };
  37037. var triggerOptions = this.actions[i].triggerOptions;
  37038. if (triggerOptions && typeof triggerOptions !== "number") {
  37039. if (triggerOptions.parameter instanceof BABYLON.Node) {
  37040. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  37041. }
  37042. else {
  37043. var parameter = {};
  37044. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  37045. if (triggerOptions.parameter.mesh) {
  37046. parameter._meshId = triggerOptions.parameter.mesh.id;
  37047. }
  37048. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  37049. }
  37050. }
  37051. // Serialize child action, recursively
  37052. this.actions[i].serialize(triggerObject);
  37053. // Add serialized trigger
  37054. root.children.push(triggerObject);
  37055. }
  37056. return root;
  37057. };
  37058. ActionManager.Parse = function (parsedActions, object, scene) {
  37059. var actionManager = new BABYLON.ActionManager(scene);
  37060. if (object === null)
  37061. scene.actionManager = actionManager;
  37062. else
  37063. object.actionManager = actionManager;
  37064. // instanciate a new object
  37065. var instanciate = function (name, params) {
  37066. var newInstance = Object.create(BABYLON[name].prototype);
  37067. newInstance.constructor.apply(newInstance, params);
  37068. return newInstance;
  37069. };
  37070. var parseParameter = function (name, value, target, propertyPath) {
  37071. if (propertyPath === null) {
  37072. // String, boolean or float
  37073. var floatValue = parseFloat(value);
  37074. if (value === "true" || value === "false")
  37075. return value === "true";
  37076. else
  37077. return isNaN(floatValue) ? value : floatValue;
  37078. }
  37079. var effectiveTarget = propertyPath.split(".");
  37080. var values = value.split(",");
  37081. // Get effective Target
  37082. for (var i = 0; i < effectiveTarget.length; i++) {
  37083. target = target[effectiveTarget[i]];
  37084. }
  37085. // Return appropriate value with its type
  37086. if (typeof (target) === "boolean")
  37087. return values[0] === "true";
  37088. if (typeof (target) === "string")
  37089. return values[0];
  37090. // Parameters with multiple values such as Vector3 etc.
  37091. var split = new Array();
  37092. for (var i = 0; i < values.length; i++)
  37093. split.push(parseFloat(values[i]));
  37094. if (target instanceof BABYLON.Vector3)
  37095. return BABYLON.Vector3.FromArray(split);
  37096. if (target instanceof BABYLON.Vector4)
  37097. return BABYLON.Vector4.FromArray(split);
  37098. if (target instanceof BABYLON.Color3)
  37099. return BABYLON.Color3.FromArray(split);
  37100. if (target instanceof BABYLON.Color4)
  37101. return BABYLON.Color4.FromArray(split);
  37102. return parseFloat(values[0]);
  37103. };
  37104. // traverse graph per trigger
  37105. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  37106. if (combineArray === void 0) { combineArray = null; }
  37107. if (parsedAction.detached)
  37108. return;
  37109. var parameters = new Array();
  37110. var target = null;
  37111. var propertyPath = null;
  37112. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  37113. // Parameters
  37114. if (parsedAction.type === 2)
  37115. parameters.push(actionManager);
  37116. else
  37117. parameters.push(trigger);
  37118. if (combine) {
  37119. var actions = new Array();
  37120. for (var j = 0; j < parsedAction.combine.length; j++) {
  37121. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  37122. }
  37123. parameters.push(actions);
  37124. }
  37125. else {
  37126. for (var i = 0; i < parsedAction.properties.length; i++) {
  37127. var value = parsedAction.properties[i].value;
  37128. var name = parsedAction.properties[i].name;
  37129. var targetType = parsedAction.properties[i].targetType;
  37130. if (name === "target")
  37131. if (targetType !== null && targetType === "SceneProperties")
  37132. value = target = scene;
  37133. else
  37134. value = target = scene.getNodeByName(value);
  37135. else if (name === "parent")
  37136. value = scene.getNodeByName(value);
  37137. else if (name === "sound")
  37138. value = scene.getSoundByName(value);
  37139. else if (name !== "propertyPath") {
  37140. if (parsedAction.type === 2 && name === "operator")
  37141. value = BABYLON.ValueCondition[value];
  37142. else
  37143. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  37144. }
  37145. else {
  37146. propertyPath = value;
  37147. }
  37148. parameters.push(value);
  37149. }
  37150. }
  37151. if (combineArray === null) {
  37152. parameters.push(condition);
  37153. }
  37154. else {
  37155. parameters.push(null);
  37156. }
  37157. // If interpolate value action
  37158. if (parsedAction.name === "InterpolateValueAction") {
  37159. var param = parameters[parameters.length - 2];
  37160. parameters[parameters.length - 1] = param;
  37161. parameters[parameters.length - 2] = condition;
  37162. }
  37163. // Action or condition(s) and not CombineAction
  37164. var newAction = instanciate(parsedAction.name, parameters);
  37165. if (newAction instanceof BABYLON.Condition && condition !== null) {
  37166. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  37167. if (action)
  37168. action.then(nothing);
  37169. else
  37170. actionManager.registerAction(nothing);
  37171. action = nothing;
  37172. }
  37173. if (combineArray === null) {
  37174. if (newAction instanceof BABYLON.Condition) {
  37175. condition = newAction;
  37176. newAction = action;
  37177. }
  37178. else {
  37179. condition = null;
  37180. if (action)
  37181. action.then(newAction);
  37182. else
  37183. actionManager.registerAction(newAction);
  37184. }
  37185. }
  37186. else {
  37187. combineArray.push(newAction);
  37188. }
  37189. for (var i = 0; i < parsedAction.children.length; i++)
  37190. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  37191. };
  37192. // triggers
  37193. for (var i = 0; i < parsedActions.children.length; i++) {
  37194. var triggerParams;
  37195. var trigger = parsedActions.children[i];
  37196. if (trigger.properties.length > 0) {
  37197. var param = trigger.properties[0].value;
  37198. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  37199. if (value._meshId) {
  37200. value.mesh = scene.getMeshByID(value._meshId);
  37201. }
  37202. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  37203. }
  37204. else
  37205. triggerParams = BABYLON.ActionManager[trigger.name];
  37206. for (var j = 0; j < trigger.children.length; j++) {
  37207. if (!trigger.detached)
  37208. traverse(trigger.children[j], triggerParams, null, null);
  37209. }
  37210. }
  37211. };
  37212. ActionManager.GetTriggerName = function (trigger) {
  37213. switch (trigger) {
  37214. case 0: return "NothingTrigger";
  37215. case 1: return "OnPickTrigger";
  37216. case 2: return "OnLeftPickTrigger";
  37217. case 3: return "OnRightPickTrigger";
  37218. case 4: return "OnCenterPickTrigger";
  37219. case 5: return "OnPickDownTrigger";
  37220. case 6: return "OnPickUpTrigger";
  37221. case 7: return "OnLongPressTrigger";
  37222. case 8: return "OnPointerOverTrigger";
  37223. case 9: return "OnPointerOutTrigger";
  37224. case 10: return "OnEveryFrameTrigger";
  37225. case 11: return "OnIntersectionEnterTrigger";
  37226. case 12: return "OnIntersectionExitTrigger";
  37227. case 13: return "OnKeyDownTrigger";
  37228. case 14: return "OnKeyUpTrigger";
  37229. case 15: return "OnPickOutTrigger";
  37230. default: return "";
  37231. }
  37232. };
  37233. return ActionManager;
  37234. }());
  37235. // Statics
  37236. ActionManager._NothingTrigger = 0;
  37237. ActionManager._OnPickTrigger = 1;
  37238. ActionManager._OnLeftPickTrigger = 2;
  37239. ActionManager._OnRightPickTrigger = 3;
  37240. ActionManager._OnCenterPickTrigger = 4;
  37241. ActionManager._OnPickDownTrigger = 5;
  37242. ActionManager._OnDoublePickTrigger = 6;
  37243. ActionManager._OnPickUpTrigger = 7;
  37244. ActionManager._OnLongPressTrigger = 8;
  37245. ActionManager._OnPointerOverTrigger = 9;
  37246. ActionManager._OnPointerOutTrigger = 10;
  37247. ActionManager._OnEveryFrameTrigger = 11;
  37248. ActionManager._OnIntersectionEnterTrigger = 12;
  37249. ActionManager._OnIntersectionExitTrigger = 13;
  37250. ActionManager._OnKeyDownTrigger = 14;
  37251. ActionManager._OnKeyUpTrigger = 15;
  37252. ActionManager._OnPickOutTrigger = 16;
  37253. ActionManager.Triggers = {};
  37254. BABYLON.ActionManager = ActionManager;
  37255. })(BABYLON || (BABYLON = {}));
  37256. //# sourceMappingURL=babylon.actionManager.js.map
  37257. var BABYLON;
  37258. (function (BABYLON) {
  37259. var InterpolateValueAction = (function (_super) {
  37260. __extends(InterpolateValueAction, _super);
  37261. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  37262. if (duration === void 0) { duration = 1000; }
  37263. var _this = _super.call(this, triggerOptions, condition) || this;
  37264. _this.propertyPath = propertyPath;
  37265. _this.value = value;
  37266. _this.duration = duration;
  37267. _this.stopOtherAnimations = stopOtherAnimations;
  37268. _this.onInterpolationDone = onInterpolationDone;
  37269. _this._target = _this._effectiveTarget = target;
  37270. return _this;
  37271. }
  37272. InterpolateValueAction.prototype._prepare = function () {
  37273. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37274. this._property = this._getProperty(this.propertyPath);
  37275. };
  37276. InterpolateValueAction.prototype.execute = function () {
  37277. var scene = this._actionManager.getScene();
  37278. var keys = [
  37279. {
  37280. frame: 0,
  37281. value: this._effectiveTarget[this._property]
  37282. }, {
  37283. frame: 100,
  37284. value: this.value
  37285. }
  37286. ];
  37287. var dataType;
  37288. if (typeof this.value === "number") {
  37289. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  37290. }
  37291. else if (this.value instanceof BABYLON.Color3) {
  37292. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  37293. }
  37294. else if (this.value instanceof BABYLON.Vector3) {
  37295. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  37296. }
  37297. else if (this.value instanceof BABYLON.Matrix) {
  37298. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  37299. }
  37300. else if (this.value instanceof BABYLON.Quaternion) {
  37301. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  37302. }
  37303. else {
  37304. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  37305. return;
  37306. }
  37307. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37308. animation.setKeys(keys);
  37309. if (this.stopOtherAnimations) {
  37310. scene.stopAnimation(this._effectiveTarget);
  37311. }
  37312. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  37313. };
  37314. InterpolateValueAction.prototype.serialize = function (parent) {
  37315. return _super.prototype._serialize.call(this, {
  37316. name: "InterpolateValueAction",
  37317. properties: [
  37318. BABYLON.Action._GetTargetProperty(this._target),
  37319. { name: "propertyPath", value: this.propertyPath },
  37320. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37321. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  37322. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  37323. ]
  37324. }, parent);
  37325. };
  37326. return InterpolateValueAction;
  37327. }(BABYLON.Action));
  37328. BABYLON.InterpolateValueAction = InterpolateValueAction;
  37329. })(BABYLON || (BABYLON = {}));
  37330. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  37331. var BABYLON;
  37332. (function (BABYLON) {
  37333. var SwitchBooleanAction = (function (_super) {
  37334. __extends(SwitchBooleanAction, _super);
  37335. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  37336. var _this = _super.call(this, triggerOptions, condition) || this;
  37337. _this.propertyPath = propertyPath;
  37338. _this._target = _this._effectiveTarget = target;
  37339. return _this;
  37340. }
  37341. SwitchBooleanAction.prototype._prepare = function () {
  37342. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37343. this._property = this._getProperty(this.propertyPath);
  37344. };
  37345. SwitchBooleanAction.prototype.execute = function () {
  37346. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  37347. };
  37348. SwitchBooleanAction.prototype.serialize = function (parent) {
  37349. return _super.prototype._serialize.call(this, {
  37350. name: "SwitchBooleanAction",
  37351. properties: [
  37352. BABYLON.Action._GetTargetProperty(this._target),
  37353. { name: "propertyPath", value: this.propertyPath }
  37354. ]
  37355. }, parent);
  37356. };
  37357. return SwitchBooleanAction;
  37358. }(BABYLON.Action));
  37359. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  37360. var SetStateAction = (function (_super) {
  37361. __extends(SetStateAction, _super);
  37362. function SetStateAction(triggerOptions, target, value, condition) {
  37363. var _this = _super.call(this, triggerOptions, condition) || this;
  37364. _this.value = value;
  37365. _this._target = target;
  37366. return _this;
  37367. }
  37368. SetStateAction.prototype.execute = function () {
  37369. this._target.state = this.value;
  37370. };
  37371. SetStateAction.prototype.serialize = function (parent) {
  37372. return _super.prototype._serialize.call(this, {
  37373. name: "SetStateAction",
  37374. properties: [
  37375. BABYLON.Action._GetTargetProperty(this._target),
  37376. { name: "value", value: this.value }
  37377. ]
  37378. }, parent);
  37379. };
  37380. return SetStateAction;
  37381. }(BABYLON.Action));
  37382. BABYLON.SetStateAction = SetStateAction;
  37383. var SetValueAction = (function (_super) {
  37384. __extends(SetValueAction, _super);
  37385. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  37386. var _this = _super.call(this, triggerOptions, condition) || this;
  37387. _this.propertyPath = propertyPath;
  37388. _this.value = value;
  37389. _this._target = _this._effectiveTarget = target;
  37390. return _this;
  37391. }
  37392. SetValueAction.prototype._prepare = function () {
  37393. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37394. this._property = this._getProperty(this.propertyPath);
  37395. };
  37396. SetValueAction.prototype.execute = function () {
  37397. this._effectiveTarget[this._property] = this.value;
  37398. if (this._target.markAsDirty) {
  37399. this._target.markAsDirty(this._property);
  37400. }
  37401. };
  37402. SetValueAction.prototype.serialize = function (parent) {
  37403. return _super.prototype._serialize.call(this, {
  37404. name: "SetValueAction",
  37405. properties: [
  37406. BABYLON.Action._GetTargetProperty(this._target),
  37407. { name: "propertyPath", value: this.propertyPath },
  37408. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37409. ]
  37410. }, parent);
  37411. };
  37412. return SetValueAction;
  37413. }(BABYLON.Action));
  37414. BABYLON.SetValueAction = SetValueAction;
  37415. var IncrementValueAction = (function (_super) {
  37416. __extends(IncrementValueAction, _super);
  37417. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  37418. var _this = _super.call(this, triggerOptions, condition) || this;
  37419. _this.propertyPath = propertyPath;
  37420. _this.value = value;
  37421. _this._target = _this._effectiveTarget = target;
  37422. return _this;
  37423. }
  37424. IncrementValueAction.prototype._prepare = function () {
  37425. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37426. this._property = this._getProperty(this.propertyPath);
  37427. if (typeof this._effectiveTarget[this._property] !== "number") {
  37428. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  37429. }
  37430. };
  37431. IncrementValueAction.prototype.execute = function () {
  37432. this._effectiveTarget[this._property] += this.value;
  37433. if (this._target.markAsDirty) {
  37434. this._target.markAsDirty(this._property);
  37435. }
  37436. };
  37437. IncrementValueAction.prototype.serialize = function (parent) {
  37438. return _super.prototype._serialize.call(this, {
  37439. name: "IncrementValueAction",
  37440. properties: [
  37441. BABYLON.Action._GetTargetProperty(this._target),
  37442. { name: "propertyPath", value: this.propertyPath },
  37443. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37444. ]
  37445. }, parent);
  37446. };
  37447. return IncrementValueAction;
  37448. }(BABYLON.Action));
  37449. BABYLON.IncrementValueAction = IncrementValueAction;
  37450. var PlayAnimationAction = (function (_super) {
  37451. __extends(PlayAnimationAction, _super);
  37452. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  37453. var _this = _super.call(this, triggerOptions, condition) || this;
  37454. _this.from = from;
  37455. _this.to = to;
  37456. _this.loop = loop;
  37457. _this._target = target;
  37458. return _this;
  37459. }
  37460. PlayAnimationAction.prototype._prepare = function () {
  37461. };
  37462. PlayAnimationAction.prototype.execute = function () {
  37463. var scene = this._actionManager.getScene();
  37464. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  37465. };
  37466. PlayAnimationAction.prototype.serialize = function (parent) {
  37467. return _super.prototype._serialize.call(this, {
  37468. name: "PlayAnimationAction",
  37469. properties: [
  37470. BABYLON.Action._GetTargetProperty(this._target),
  37471. { name: "from", value: String(this.from) },
  37472. { name: "to", value: String(this.to) },
  37473. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  37474. ]
  37475. }, parent);
  37476. };
  37477. return PlayAnimationAction;
  37478. }(BABYLON.Action));
  37479. BABYLON.PlayAnimationAction = PlayAnimationAction;
  37480. var StopAnimationAction = (function (_super) {
  37481. __extends(StopAnimationAction, _super);
  37482. function StopAnimationAction(triggerOptions, target, condition) {
  37483. var _this = _super.call(this, triggerOptions, condition) || this;
  37484. _this._target = target;
  37485. return _this;
  37486. }
  37487. StopAnimationAction.prototype._prepare = function () {
  37488. };
  37489. StopAnimationAction.prototype.execute = function () {
  37490. var scene = this._actionManager.getScene();
  37491. scene.stopAnimation(this._target);
  37492. };
  37493. StopAnimationAction.prototype.serialize = function (parent) {
  37494. return _super.prototype._serialize.call(this, {
  37495. name: "StopAnimationAction",
  37496. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  37497. }, parent);
  37498. };
  37499. return StopAnimationAction;
  37500. }(BABYLON.Action));
  37501. BABYLON.StopAnimationAction = StopAnimationAction;
  37502. var DoNothingAction = (function (_super) {
  37503. __extends(DoNothingAction, _super);
  37504. function DoNothingAction(triggerOptions, condition) {
  37505. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  37506. return _super.call(this, triggerOptions, condition) || this;
  37507. }
  37508. DoNothingAction.prototype.execute = function () {
  37509. };
  37510. DoNothingAction.prototype.serialize = function (parent) {
  37511. return _super.prototype._serialize.call(this, {
  37512. name: "DoNothingAction",
  37513. properties: []
  37514. }, parent);
  37515. };
  37516. return DoNothingAction;
  37517. }(BABYLON.Action));
  37518. BABYLON.DoNothingAction = DoNothingAction;
  37519. var CombineAction = (function (_super) {
  37520. __extends(CombineAction, _super);
  37521. function CombineAction(triggerOptions, children, condition) {
  37522. var _this = _super.call(this, triggerOptions, condition) || this;
  37523. _this.children = children;
  37524. return _this;
  37525. }
  37526. CombineAction.prototype._prepare = function () {
  37527. for (var index = 0; index < this.children.length; index++) {
  37528. this.children[index]._actionManager = this._actionManager;
  37529. this.children[index]._prepare();
  37530. }
  37531. };
  37532. CombineAction.prototype.execute = function (evt) {
  37533. for (var index = 0; index < this.children.length; index++) {
  37534. this.children[index].execute(evt);
  37535. }
  37536. };
  37537. CombineAction.prototype.serialize = function (parent) {
  37538. var serializationObject = _super.prototype._serialize.call(this, {
  37539. name: "CombineAction",
  37540. properties: [],
  37541. combine: []
  37542. }, parent);
  37543. for (var i = 0; i < this.children.length; i++) {
  37544. serializationObject.combine.push(this.children[i].serialize(null));
  37545. }
  37546. return serializationObject;
  37547. };
  37548. return CombineAction;
  37549. }(BABYLON.Action));
  37550. BABYLON.CombineAction = CombineAction;
  37551. var ExecuteCodeAction = (function (_super) {
  37552. __extends(ExecuteCodeAction, _super);
  37553. function ExecuteCodeAction(triggerOptions, func, condition) {
  37554. var _this = _super.call(this, triggerOptions, condition) || this;
  37555. _this.func = func;
  37556. return _this;
  37557. }
  37558. ExecuteCodeAction.prototype.execute = function (evt) {
  37559. this.func(evt);
  37560. };
  37561. return ExecuteCodeAction;
  37562. }(BABYLON.Action));
  37563. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  37564. var SetParentAction = (function (_super) {
  37565. __extends(SetParentAction, _super);
  37566. function SetParentAction(triggerOptions, target, parent, condition) {
  37567. var _this = _super.call(this, triggerOptions, condition) || this;
  37568. _this._target = target;
  37569. _this._parent = parent;
  37570. return _this;
  37571. }
  37572. SetParentAction.prototype._prepare = function () {
  37573. };
  37574. SetParentAction.prototype.execute = function () {
  37575. if (this._target.parent === this._parent) {
  37576. return;
  37577. }
  37578. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  37579. invertParentWorldMatrix.invert();
  37580. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  37581. this._target.parent = this._parent;
  37582. };
  37583. SetParentAction.prototype.serialize = function (parent) {
  37584. return _super.prototype._serialize.call(this, {
  37585. name: "SetParentAction",
  37586. properties: [
  37587. BABYLON.Action._GetTargetProperty(this._target),
  37588. BABYLON.Action._GetTargetProperty(this._parent),
  37589. ]
  37590. }, parent);
  37591. };
  37592. return SetParentAction;
  37593. }(BABYLON.Action));
  37594. BABYLON.SetParentAction = SetParentAction;
  37595. var PlaySoundAction = (function (_super) {
  37596. __extends(PlaySoundAction, _super);
  37597. function PlaySoundAction(triggerOptions, sound, condition) {
  37598. var _this = _super.call(this, triggerOptions, condition) || this;
  37599. _this._sound = sound;
  37600. return _this;
  37601. }
  37602. PlaySoundAction.prototype._prepare = function () {
  37603. };
  37604. PlaySoundAction.prototype.execute = function () {
  37605. if (this._sound !== undefined)
  37606. this._sound.play();
  37607. };
  37608. PlaySoundAction.prototype.serialize = function (parent) {
  37609. return _super.prototype._serialize.call(this, {
  37610. name: "PlaySoundAction",
  37611. properties: [{ name: "sound", value: this._sound.name }]
  37612. }, parent);
  37613. };
  37614. return PlaySoundAction;
  37615. }(BABYLON.Action));
  37616. BABYLON.PlaySoundAction = PlaySoundAction;
  37617. var StopSoundAction = (function (_super) {
  37618. __extends(StopSoundAction, _super);
  37619. function StopSoundAction(triggerOptions, sound, condition) {
  37620. var _this = _super.call(this, triggerOptions, condition) || this;
  37621. _this._sound = sound;
  37622. return _this;
  37623. }
  37624. StopSoundAction.prototype._prepare = function () {
  37625. };
  37626. StopSoundAction.prototype.execute = function () {
  37627. if (this._sound !== undefined)
  37628. this._sound.stop();
  37629. };
  37630. StopSoundAction.prototype.serialize = function (parent) {
  37631. return _super.prototype._serialize.call(this, {
  37632. name: "StopSoundAction",
  37633. properties: [{ name: "sound", value: this._sound.name }]
  37634. }, parent);
  37635. };
  37636. return StopSoundAction;
  37637. }(BABYLON.Action));
  37638. BABYLON.StopSoundAction = StopSoundAction;
  37639. })(BABYLON || (BABYLON = {}));
  37640. //# sourceMappingURL=babylon.directActions.js.map
  37641. var BABYLON;
  37642. (function (BABYLON) {
  37643. var SpriteManager = (function () {
  37644. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  37645. if (epsilon === void 0) { epsilon = 0.01; }
  37646. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37647. this.name = name;
  37648. this.sprites = new Array();
  37649. this.renderingGroupId = 0;
  37650. this.layerMask = 0x0FFFFFFF;
  37651. this.fogEnabled = true;
  37652. this.isPickable = false;
  37653. /**
  37654. * An event triggered when the manager is disposed.
  37655. * @type {BABYLON.Observable}
  37656. */
  37657. this.onDisposeObservable = new BABYLON.Observable();
  37658. this._vertexBuffers = {};
  37659. this._capacity = capacity;
  37660. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  37661. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37662. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37663. if (cellSize.width && cellSize.height) {
  37664. this.cellWidth = cellSize.width;
  37665. this.cellHeight = cellSize.height;
  37666. }
  37667. else if (cellSize !== undefined) {
  37668. this.cellWidth = cellSize;
  37669. this.cellHeight = cellSize;
  37670. }
  37671. else {
  37672. return;
  37673. }
  37674. this._epsilon = epsilon;
  37675. this._scene = scene;
  37676. this._scene.spriteManagers.push(this);
  37677. var indices = [];
  37678. var index = 0;
  37679. for (var count = 0; count < capacity; count++) {
  37680. indices.push(index);
  37681. indices.push(index + 1);
  37682. indices.push(index + 2);
  37683. indices.push(index);
  37684. indices.push(index + 2);
  37685. indices.push(index + 3);
  37686. index += 4;
  37687. }
  37688. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  37689. // VBO
  37690. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  37691. this._vertexData = new Float32Array(capacity * 16 * 4);
  37692. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  37693. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  37694. var options = this._buffer.createVertexBuffer("options", 4, 4);
  37695. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  37696. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  37697. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  37698. this._vertexBuffers["options"] = options;
  37699. this._vertexBuffers["cellInfo"] = cellInfo;
  37700. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  37701. // Effects
  37702. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  37703. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  37704. }
  37705. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  37706. set: function (callback) {
  37707. if (this._onDisposeObserver) {
  37708. this.onDisposeObservable.remove(this._onDisposeObserver);
  37709. }
  37710. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  37711. },
  37712. enumerable: true,
  37713. configurable: true
  37714. });
  37715. Object.defineProperty(SpriteManager.prototype, "texture", {
  37716. get: function () {
  37717. return this._spriteTexture;
  37718. },
  37719. set: function (value) {
  37720. this._spriteTexture = value;
  37721. },
  37722. enumerable: true,
  37723. configurable: true
  37724. });
  37725. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  37726. var arrayOffset = index * 16;
  37727. if (offsetX === 0)
  37728. offsetX = this._epsilon;
  37729. else if (offsetX === 1)
  37730. offsetX = 1 - this._epsilon;
  37731. if (offsetY === 0)
  37732. offsetY = this._epsilon;
  37733. else if (offsetY === 1)
  37734. offsetY = 1 - this._epsilon;
  37735. this._vertexData[arrayOffset] = sprite.position.x;
  37736. this._vertexData[arrayOffset + 1] = sprite.position.y;
  37737. this._vertexData[arrayOffset + 2] = sprite.position.z;
  37738. this._vertexData[arrayOffset + 3] = sprite.angle;
  37739. this._vertexData[arrayOffset + 4] = sprite.width;
  37740. this._vertexData[arrayOffset + 5] = sprite.height;
  37741. this._vertexData[arrayOffset + 6] = offsetX;
  37742. this._vertexData[arrayOffset + 7] = offsetY;
  37743. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  37744. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  37745. var offset = (sprite.cellIndex / rowSize) >> 0;
  37746. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  37747. this._vertexData[arrayOffset + 11] = offset;
  37748. // Color
  37749. this._vertexData[arrayOffset + 12] = sprite.color.r;
  37750. this._vertexData[arrayOffset + 13] = sprite.color.g;
  37751. this._vertexData[arrayOffset + 14] = sprite.color.b;
  37752. this._vertexData[arrayOffset + 15] = sprite.color.a;
  37753. };
  37754. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  37755. var count = Math.min(this._capacity, this.sprites.length);
  37756. var min = BABYLON.Vector3.Zero();
  37757. var max = BABYLON.Vector3.Zero();
  37758. var distance = Number.MAX_VALUE;
  37759. var currentSprite;
  37760. var cameraSpacePosition = BABYLON.Vector3.Zero();
  37761. var cameraView = camera.getViewMatrix();
  37762. for (var index = 0; index < count; index++) {
  37763. var sprite = this.sprites[index];
  37764. if (!sprite) {
  37765. continue;
  37766. }
  37767. if (predicate) {
  37768. if (!predicate(sprite)) {
  37769. continue;
  37770. }
  37771. }
  37772. else if (!sprite.isPickable) {
  37773. continue;
  37774. }
  37775. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  37776. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  37777. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  37778. if (ray.intersectsBoxMinMax(min, max)) {
  37779. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  37780. if (distance > currentDistance) {
  37781. distance = currentDistance;
  37782. currentSprite = sprite;
  37783. if (fastCheck) {
  37784. break;
  37785. }
  37786. }
  37787. }
  37788. }
  37789. if (currentSprite) {
  37790. var result = new BABYLON.PickingInfo();
  37791. result.hit = true;
  37792. result.pickedSprite = currentSprite;
  37793. result.distance = distance;
  37794. return result;
  37795. }
  37796. return null;
  37797. };
  37798. SpriteManager.prototype.render = function () {
  37799. // Check
  37800. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  37801. return;
  37802. var engine = this._scene.getEngine();
  37803. var baseSize = this._spriteTexture.getBaseSize();
  37804. // Sprites
  37805. var deltaTime = engine.getDeltaTime();
  37806. var max = Math.min(this._capacity, this.sprites.length);
  37807. var rowSize = baseSize.width / this.cellWidth;
  37808. var offset = 0;
  37809. for (var index = 0; index < max; index++) {
  37810. var sprite = this.sprites[index];
  37811. if (!sprite) {
  37812. continue;
  37813. }
  37814. sprite._animate(deltaTime);
  37815. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  37816. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  37817. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  37818. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  37819. }
  37820. this._buffer.update(this._vertexData);
  37821. // Render
  37822. var effect = this._effectBase;
  37823. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  37824. effect = this._effectFog;
  37825. }
  37826. engine.enableEffect(effect);
  37827. var viewMatrix = this._scene.getViewMatrix();
  37828. effect.setTexture("diffuseSampler", this._spriteTexture);
  37829. effect.setMatrix("view", viewMatrix);
  37830. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  37831. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  37832. // Fog
  37833. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  37834. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  37835. effect.setColor3("vFogColor", this._scene.fogColor);
  37836. }
  37837. // VBOs
  37838. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37839. // Draw order
  37840. engine.setDepthFunctionToLessOrEqual();
  37841. effect.setBool("alphaTest", true);
  37842. engine.setColorWrite(false);
  37843. engine.draw(true, 0, max * 6);
  37844. engine.setColorWrite(true);
  37845. effect.setBool("alphaTest", false);
  37846. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  37847. engine.draw(true, 0, max * 6);
  37848. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37849. };
  37850. SpriteManager.prototype.dispose = function () {
  37851. if (this._buffer) {
  37852. this._buffer.dispose();
  37853. this._buffer = null;
  37854. }
  37855. if (this._indexBuffer) {
  37856. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37857. this._indexBuffer = null;
  37858. }
  37859. if (this._spriteTexture) {
  37860. this._spriteTexture.dispose();
  37861. this._spriteTexture = null;
  37862. }
  37863. // Remove from scene
  37864. var index = this._scene.spriteManagers.indexOf(this);
  37865. this._scene.spriteManagers.splice(index, 1);
  37866. // Callback
  37867. this.onDisposeObservable.notifyObservers(this);
  37868. this.onDisposeObservable.clear();
  37869. };
  37870. return SpriteManager;
  37871. }());
  37872. BABYLON.SpriteManager = SpriteManager;
  37873. })(BABYLON || (BABYLON = {}));
  37874. //# sourceMappingURL=babylon.spriteManager.js.map
  37875. var BABYLON;
  37876. (function (BABYLON) {
  37877. var Sprite = (function () {
  37878. function Sprite(name, manager) {
  37879. this.name = name;
  37880. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37881. this.width = 1.0;
  37882. this.height = 1.0;
  37883. this.angle = 0;
  37884. this.cellIndex = 0;
  37885. this.invertU = 0;
  37886. this.invertV = 0;
  37887. this.animations = new Array();
  37888. this.isPickable = false;
  37889. this._animationStarted = false;
  37890. this._loopAnimation = false;
  37891. this._fromIndex = 0;
  37892. this._toIndex = 0;
  37893. this._delay = 0;
  37894. this._direction = 1;
  37895. this._frameCount = 0;
  37896. this._time = 0;
  37897. this._manager = manager;
  37898. this._manager.sprites.push(this);
  37899. this.position = BABYLON.Vector3.Zero();
  37900. }
  37901. Object.defineProperty(Sprite.prototype, "size", {
  37902. get: function () {
  37903. return this.width;
  37904. },
  37905. set: function (value) {
  37906. this.width = value;
  37907. this.height = value;
  37908. },
  37909. enumerable: true,
  37910. configurable: true
  37911. });
  37912. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  37913. this._fromIndex = from;
  37914. this._toIndex = to;
  37915. this._loopAnimation = loop;
  37916. this._delay = delay;
  37917. this._animationStarted = true;
  37918. this._direction = from < to ? 1 : -1;
  37919. this.cellIndex = from;
  37920. this._time = 0;
  37921. this._onAnimationEnd = onAnimationEnd;
  37922. };
  37923. Sprite.prototype.stopAnimation = function () {
  37924. this._animationStarted = false;
  37925. };
  37926. Sprite.prototype._animate = function (deltaTime) {
  37927. if (!this._animationStarted)
  37928. return;
  37929. this._time += deltaTime;
  37930. if (this._time > this._delay) {
  37931. this._time = this._time % this._delay;
  37932. this.cellIndex += this._direction;
  37933. if (this.cellIndex === this._toIndex) {
  37934. if (this._loopAnimation) {
  37935. this.cellIndex = this._fromIndex;
  37936. }
  37937. else {
  37938. this._animationStarted = false;
  37939. if (this._onAnimationEnd) {
  37940. this._onAnimationEnd();
  37941. }
  37942. if (this.disposeWhenFinishedAnimating) {
  37943. this.dispose();
  37944. }
  37945. }
  37946. }
  37947. }
  37948. };
  37949. Sprite.prototype.dispose = function () {
  37950. for (var i = 0; i < this._manager.sprites.length; i++) {
  37951. if (this._manager.sprites[i] == this) {
  37952. this._manager.sprites.splice(i, 1);
  37953. }
  37954. }
  37955. };
  37956. return Sprite;
  37957. }());
  37958. BABYLON.Sprite = Sprite;
  37959. })(BABYLON || (BABYLON = {}));
  37960. //# sourceMappingURL=babylon.sprite.js.map
  37961. var BABYLON;
  37962. (function (BABYLON) {
  37963. var IntersectionInfo = (function () {
  37964. function IntersectionInfo(bu, bv, distance) {
  37965. this.bu = bu;
  37966. this.bv = bv;
  37967. this.distance = distance;
  37968. this.faceId = 0;
  37969. this.subMeshId = 0;
  37970. }
  37971. return IntersectionInfo;
  37972. }());
  37973. BABYLON.IntersectionInfo = IntersectionInfo;
  37974. var PickingInfo = (function () {
  37975. function PickingInfo() {
  37976. this.hit = false;
  37977. this.distance = 0;
  37978. this.pickedPoint = null;
  37979. this.pickedMesh = null;
  37980. this.bu = 0;
  37981. this.bv = 0;
  37982. this.faceId = -1;
  37983. this.subMeshId = 0;
  37984. this.pickedSprite = null;
  37985. }
  37986. // Methods
  37987. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  37988. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  37989. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  37990. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37991. return null;
  37992. }
  37993. var indices = this.pickedMesh.getIndices();
  37994. var result;
  37995. if (useVerticesNormals) {
  37996. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37997. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  37998. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  37999. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  38000. normal0 = normal0.scale(this.bu);
  38001. normal1 = normal1.scale(this.bv);
  38002. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  38003. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  38004. }
  38005. else {
  38006. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38007. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  38008. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  38009. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  38010. var p1p2 = vertex1.subtract(vertex2);
  38011. var p3p2 = vertex3.subtract(vertex2);
  38012. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  38013. }
  38014. if (useWorldCoordinates) {
  38015. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  38016. }
  38017. return BABYLON.Vector3.Normalize(result);
  38018. };
  38019. PickingInfo.prototype.getTextureCoordinates = function () {
  38020. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38021. return null;
  38022. }
  38023. var indices = this.pickedMesh.getIndices();
  38024. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38025. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  38026. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  38027. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  38028. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  38029. uv1 = uv1.scale(this.bu);
  38030. uv2 = uv2.scale(this.bv);
  38031. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  38032. };
  38033. return PickingInfo;
  38034. }());
  38035. BABYLON.PickingInfo = PickingInfo;
  38036. })(BABYLON || (BABYLON = {}));
  38037. //# sourceMappingURL=babylon.pickingInfo.js.map
  38038. var BABYLON;
  38039. (function (BABYLON) {
  38040. var Ray = (function () {
  38041. function Ray(origin, direction, length) {
  38042. if (length === void 0) { length = Number.MAX_VALUE; }
  38043. this.origin = origin;
  38044. this.direction = direction;
  38045. this.length = length;
  38046. }
  38047. // Methods
  38048. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  38049. var d = 0.0;
  38050. var maxValue = Number.MAX_VALUE;
  38051. var inv;
  38052. var min;
  38053. var max;
  38054. var temp;
  38055. if (Math.abs(this.direction.x) < 0.0000001) {
  38056. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  38057. return false;
  38058. }
  38059. }
  38060. else {
  38061. inv = 1.0 / this.direction.x;
  38062. min = (minimum.x - this.origin.x) * inv;
  38063. max = (maximum.x - this.origin.x) * inv;
  38064. if (max === -Infinity) {
  38065. max = Infinity;
  38066. }
  38067. if (min > max) {
  38068. temp = min;
  38069. min = max;
  38070. max = temp;
  38071. }
  38072. d = Math.max(min, d);
  38073. maxValue = Math.min(max, maxValue);
  38074. if (d > maxValue) {
  38075. return false;
  38076. }
  38077. }
  38078. if (Math.abs(this.direction.y) < 0.0000001) {
  38079. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  38080. return false;
  38081. }
  38082. }
  38083. else {
  38084. inv = 1.0 / this.direction.y;
  38085. min = (minimum.y - this.origin.y) * inv;
  38086. max = (maximum.y - this.origin.y) * inv;
  38087. if (max === -Infinity) {
  38088. max = Infinity;
  38089. }
  38090. if (min > max) {
  38091. temp = min;
  38092. min = max;
  38093. max = temp;
  38094. }
  38095. d = Math.max(min, d);
  38096. maxValue = Math.min(max, maxValue);
  38097. if (d > maxValue) {
  38098. return false;
  38099. }
  38100. }
  38101. if (Math.abs(this.direction.z) < 0.0000001) {
  38102. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  38103. return false;
  38104. }
  38105. }
  38106. else {
  38107. inv = 1.0 / this.direction.z;
  38108. min = (minimum.z - this.origin.z) * inv;
  38109. max = (maximum.z - this.origin.z) * inv;
  38110. if (max === -Infinity) {
  38111. max = Infinity;
  38112. }
  38113. if (min > max) {
  38114. temp = min;
  38115. min = max;
  38116. max = temp;
  38117. }
  38118. d = Math.max(min, d);
  38119. maxValue = Math.min(max, maxValue);
  38120. if (d > maxValue) {
  38121. return false;
  38122. }
  38123. }
  38124. return true;
  38125. };
  38126. Ray.prototype.intersectsBox = function (box) {
  38127. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  38128. };
  38129. Ray.prototype.intersectsSphere = function (sphere) {
  38130. var x = sphere.center.x - this.origin.x;
  38131. var y = sphere.center.y - this.origin.y;
  38132. var z = sphere.center.z - this.origin.z;
  38133. var pyth = (x * x) + (y * y) + (z * z);
  38134. var rr = sphere.radius * sphere.radius;
  38135. if (pyth <= rr) {
  38136. return true;
  38137. }
  38138. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  38139. if (dot < 0.0) {
  38140. return false;
  38141. }
  38142. var temp = pyth - (dot * dot);
  38143. return temp <= rr;
  38144. };
  38145. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  38146. if (!this._edge1) {
  38147. this._edge1 = BABYLON.Vector3.Zero();
  38148. this._edge2 = BABYLON.Vector3.Zero();
  38149. this._pvec = BABYLON.Vector3.Zero();
  38150. this._tvec = BABYLON.Vector3.Zero();
  38151. this._qvec = BABYLON.Vector3.Zero();
  38152. }
  38153. vertex1.subtractToRef(vertex0, this._edge1);
  38154. vertex2.subtractToRef(vertex0, this._edge2);
  38155. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  38156. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  38157. if (det === 0) {
  38158. return null;
  38159. }
  38160. var invdet = 1 / det;
  38161. this.origin.subtractToRef(vertex0, this._tvec);
  38162. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  38163. if (bu < 0 || bu > 1.0) {
  38164. return null;
  38165. }
  38166. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  38167. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  38168. if (bv < 0 || bu + bv > 1.0) {
  38169. return null;
  38170. }
  38171. //check if the distance is longer than the predefined length.
  38172. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  38173. if (distance > this.length) {
  38174. return null;
  38175. }
  38176. return new BABYLON.IntersectionInfo(bu, bv, distance);
  38177. };
  38178. Ray.prototype.intersectsPlane = function (plane) {
  38179. var distance;
  38180. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  38181. if (Math.abs(result1) < 9.99999997475243E-07) {
  38182. return null;
  38183. }
  38184. else {
  38185. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  38186. distance = (-plane.d - result2) / result1;
  38187. if (distance < 0.0) {
  38188. if (distance < -9.99999997475243E-07) {
  38189. return null;
  38190. }
  38191. else {
  38192. return 0;
  38193. }
  38194. }
  38195. return distance;
  38196. }
  38197. };
  38198. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  38199. var tm = BABYLON.Tmp.Matrix[0];
  38200. mesh.getWorldMatrix().invertToRef(tm);
  38201. if (this._tmpRay) {
  38202. Ray.TransformToRef(this, tm, this._tmpRay);
  38203. }
  38204. else {
  38205. this._tmpRay = Ray.Transform(this, tm);
  38206. }
  38207. return mesh.intersects(this._tmpRay, fastCheck);
  38208. };
  38209. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  38210. if (results) {
  38211. results.length = 0;
  38212. }
  38213. else {
  38214. results = [];
  38215. }
  38216. for (var i = 0; i < meshes.length; i++) {
  38217. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  38218. if (pickInfo.hit) {
  38219. results.push(pickInfo);
  38220. }
  38221. }
  38222. results.sort(this._comparePickingInfo);
  38223. return results;
  38224. };
  38225. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  38226. if (pickingInfoA.distance < pickingInfoB.distance) {
  38227. return -1;
  38228. }
  38229. else if (pickingInfoA.distance > pickingInfoB.distance) {
  38230. return 1;
  38231. }
  38232. else {
  38233. return 0;
  38234. }
  38235. };
  38236. /**
  38237. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  38238. * @param sega the first point of the segment to test the intersection against
  38239. * @param segb the second point of the segment to test the intersection against
  38240. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  38241. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  38242. */
  38243. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  38244. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  38245. var u = segb.subtract(sega);
  38246. var v = rsegb.subtract(this.origin);
  38247. var w = sega.subtract(this.origin);
  38248. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  38249. var b = BABYLON.Vector3.Dot(u, v);
  38250. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  38251. var d = BABYLON.Vector3.Dot(u, w);
  38252. var e = BABYLON.Vector3.Dot(v, w);
  38253. var D = a * c - b * b; // always >= 0
  38254. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  38255. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  38256. // compute the line parameters of the two closest points
  38257. if (D < Ray.smallnum) {
  38258. sN = 0.0; // force using point P0 on segment S1
  38259. sD = 1.0; // to prevent possible division by 0.0 later
  38260. tN = e;
  38261. tD = c;
  38262. }
  38263. else {
  38264. sN = (b * e - c * d);
  38265. tN = (a * e - b * d);
  38266. if (sN < 0.0) {
  38267. sN = 0.0;
  38268. tN = e;
  38269. tD = c;
  38270. }
  38271. else if (sN > sD) {
  38272. sN = sD;
  38273. tN = e + b;
  38274. tD = c;
  38275. }
  38276. }
  38277. if (tN < 0.0) {
  38278. tN = 0.0;
  38279. // recompute sc for this edge
  38280. if (-d < 0.0) {
  38281. sN = 0.0;
  38282. }
  38283. else if (-d > a)
  38284. sN = sD;
  38285. else {
  38286. sN = -d;
  38287. sD = a;
  38288. }
  38289. }
  38290. else if (tN > tD) {
  38291. tN = tD;
  38292. // recompute sc for this edge
  38293. if ((-d + b) < 0.0) {
  38294. sN = 0;
  38295. }
  38296. else if ((-d + b) > a) {
  38297. sN = sD;
  38298. }
  38299. else {
  38300. sN = (-d + b);
  38301. sD = a;
  38302. }
  38303. }
  38304. // finally do the division to get sc and tc
  38305. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  38306. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  38307. // get the difference of the two closest points
  38308. var qtc = v.multiplyByFloats(tc, tc, tc);
  38309. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  38310. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  38311. if (isIntersected) {
  38312. return qtc.length();
  38313. }
  38314. return -1;
  38315. };
  38316. // Statics
  38317. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  38318. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  38319. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  38320. var direction = end.subtract(start);
  38321. direction.normalize();
  38322. return new Ray(start, direction);
  38323. };
  38324. /**
  38325. * 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
  38326. * transformed to the given world matrix.
  38327. * @param origin The origin point
  38328. * @param end The end point
  38329. * @param world a matrix to transform the ray to. Default is the identity matrix.
  38330. */
  38331. Ray.CreateNewFromTo = function (origin, end, world) {
  38332. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  38333. var direction = end.subtract(origin);
  38334. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  38335. direction.normalize();
  38336. return Ray.Transform(new Ray(origin, direction, length), world);
  38337. };
  38338. Ray.Transform = function (ray, matrix) {
  38339. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  38340. Ray.TransformToRef(ray, matrix, result);
  38341. return result;
  38342. };
  38343. Ray.TransformToRef = function (ray, matrix, result) {
  38344. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  38345. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  38346. result.length = ray.length;
  38347. var dir = result.direction;
  38348. var len = dir.length();
  38349. if (!(len === 0 || len === 1)) {
  38350. var num = 1.0 / len;
  38351. dir.x *= num;
  38352. dir.y *= num;
  38353. dir.z *= num;
  38354. result.length *= len;
  38355. }
  38356. };
  38357. return Ray;
  38358. }());
  38359. Ray.smallnum = 0.00000001;
  38360. Ray.rayl = 10e8;
  38361. BABYLON.Ray = Ray;
  38362. })(BABYLON || (BABYLON = {}));
  38363. //# sourceMappingURL=babylon.ray.js.map
  38364. var BABYLON;
  38365. (function (BABYLON) {
  38366. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  38367. if (boxMin.x > sphereCenter.x + sphereRadius)
  38368. return false;
  38369. if (sphereCenter.x - sphereRadius > boxMax.x)
  38370. return false;
  38371. if (boxMin.y > sphereCenter.y + sphereRadius)
  38372. return false;
  38373. if (sphereCenter.y - sphereRadius > boxMax.y)
  38374. return false;
  38375. if (boxMin.z > sphereCenter.z + sphereRadius)
  38376. return false;
  38377. if (sphereCenter.z - sphereRadius > boxMax.z)
  38378. return false;
  38379. return true;
  38380. };
  38381. var getLowestRoot = (function () {
  38382. var result = { root: 0, found: false };
  38383. return function (a, b, c, maxR) {
  38384. result.root = 0;
  38385. result.found = false;
  38386. var determinant = b * b - 4.0 * a * c;
  38387. if (determinant < 0)
  38388. return result;
  38389. var sqrtD = Math.sqrt(determinant);
  38390. var r1 = (-b - sqrtD) / (2.0 * a);
  38391. var r2 = (-b + sqrtD) / (2.0 * a);
  38392. if (r1 > r2) {
  38393. var temp = r2;
  38394. r2 = r1;
  38395. r1 = temp;
  38396. }
  38397. if (r1 > 0 && r1 < maxR) {
  38398. result.root = r1;
  38399. result.found = true;
  38400. return result;
  38401. }
  38402. if (r2 > 0 && r2 < maxR) {
  38403. result.root = r2;
  38404. result.found = true;
  38405. return result;
  38406. }
  38407. return result;
  38408. };
  38409. })();
  38410. var Collider = (function () {
  38411. function Collider() {
  38412. this.radius = BABYLON.Vector3.One();
  38413. this.retry = 0;
  38414. this.basePointWorld = BABYLON.Vector3.Zero();
  38415. this.velocityWorld = BABYLON.Vector3.Zero();
  38416. this.normalizedVelocity = BABYLON.Vector3.Zero();
  38417. this._collisionPoint = BABYLON.Vector3.Zero();
  38418. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  38419. this._tempVector = BABYLON.Vector3.Zero();
  38420. this._tempVector2 = BABYLON.Vector3.Zero();
  38421. this._tempVector3 = BABYLON.Vector3.Zero();
  38422. this._tempVector4 = BABYLON.Vector3.Zero();
  38423. this._edge = BABYLON.Vector3.Zero();
  38424. this._baseToVertex = BABYLON.Vector3.Zero();
  38425. this._destinationPoint = BABYLON.Vector3.Zero();
  38426. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  38427. this._displacementVector = BABYLON.Vector3.Zero();
  38428. this._collisionMask = -1;
  38429. }
  38430. Object.defineProperty(Collider.prototype, "collisionMask", {
  38431. get: function () {
  38432. return this._collisionMask;
  38433. },
  38434. set: function (mask) {
  38435. this._collisionMask = !isNaN(mask) ? mask : -1;
  38436. },
  38437. enumerable: true,
  38438. configurable: true
  38439. });
  38440. // Methods
  38441. Collider.prototype._initialize = function (source, dir, e) {
  38442. this.velocity = dir;
  38443. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  38444. this.basePoint = source;
  38445. source.multiplyToRef(this.radius, this.basePointWorld);
  38446. dir.multiplyToRef(this.radius, this.velocityWorld);
  38447. this.velocityWorldLength = this.velocityWorld.length();
  38448. this.epsilon = e;
  38449. this.collisionFound = false;
  38450. };
  38451. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  38452. pa.subtractToRef(point, this._tempVector);
  38453. pb.subtractToRef(point, this._tempVector2);
  38454. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  38455. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  38456. if (d < 0)
  38457. return false;
  38458. pc.subtractToRef(point, this._tempVector3);
  38459. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  38460. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  38461. if (d < 0)
  38462. return false;
  38463. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  38464. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  38465. return d >= 0;
  38466. };
  38467. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  38468. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  38469. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  38470. if (distance > this.velocityWorldLength + max + sphereRadius) {
  38471. return false;
  38472. }
  38473. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  38474. return false;
  38475. return true;
  38476. };
  38477. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  38478. var t0;
  38479. var embeddedInPlane = false;
  38480. //defensive programming, actually not needed.
  38481. if (!trianglePlaneArray) {
  38482. trianglePlaneArray = [];
  38483. }
  38484. if (!trianglePlaneArray[faceIndex]) {
  38485. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  38486. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  38487. }
  38488. var trianglePlane = trianglePlaneArray[faceIndex];
  38489. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  38490. return;
  38491. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  38492. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  38493. if (normalDotVelocity == 0) {
  38494. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  38495. return;
  38496. embeddedInPlane = true;
  38497. t0 = 0;
  38498. }
  38499. else {
  38500. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  38501. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  38502. if (t0 > t1) {
  38503. var temp = t1;
  38504. t1 = t0;
  38505. t0 = temp;
  38506. }
  38507. if (t0 > 1.0 || t1 < 0.0)
  38508. return;
  38509. if (t0 < 0)
  38510. t0 = 0;
  38511. if (t0 > 1.0)
  38512. t0 = 1.0;
  38513. }
  38514. this._collisionPoint.copyFromFloats(0, 0, 0);
  38515. var found = false;
  38516. var t = 1.0;
  38517. if (!embeddedInPlane) {
  38518. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  38519. this.velocity.scaleToRef(t0, this._tempVector);
  38520. this._planeIntersectionPoint.addInPlace(this._tempVector);
  38521. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  38522. found = true;
  38523. t = t0;
  38524. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  38525. }
  38526. }
  38527. if (!found) {
  38528. var velocitySquaredLength = this.velocity.lengthSquared();
  38529. var a = velocitySquaredLength;
  38530. this.basePoint.subtractToRef(p1, this._tempVector);
  38531. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  38532. var c = this._tempVector.lengthSquared() - 1.0;
  38533. var lowestRoot = getLowestRoot(a, b, c, t);
  38534. if (lowestRoot.found) {
  38535. t = lowestRoot.root;
  38536. found = true;
  38537. this._collisionPoint.copyFrom(p1);
  38538. }
  38539. this.basePoint.subtractToRef(p2, this._tempVector);
  38540. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  38541. c = this._tempVector.lengthSquared() - 1.0;
  38542. lowestRoot = getLowestRoot(a, b, c, t);
  38543. if (lowestRoot.found) {
  38544. t = lowestRoot.root;
  38545. found = true;
  38546. this._collisionPoint.copyFrom(p2);
  38547. }
  38548. this.basePoint.subtractToRef(p3, this._tempVector);
  38549. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  38550. c = this._tempVector.lengthSquared() - 1.0;
  38551. lowestRoot = getLowestRoot(a, b, c, t);
  38552. if (lowestRoot.found) {
  38553. t = lowestRoot.root;
  38554. found = true;
  38555. this._collisionPoint.copyFrom(p3);
  38556. }
  38557. p2.subtractToRef(p1, this._edge);
  38558. p1.subtractToRef(this.basePoint, this._baseToVertex);
  38559. var edgeSquaredLength = this._edge.lengthSquared();
  38560. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  38561. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  38562. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  38563. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  38564. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  38565. lowestRoot = getLowestRoot(a, b, c, t);
  38566. if (lowestRoot.found) {
  38567. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  38568. if (f >= 0.0 && f <= 1.0) {
  38569. t = lowestRoot.root;
  38570. found = true;
  38571. this._edge.scaleInPlace(f);
  38572. p1.addToRef(this._edge, this._collisionPoint);
  38573. }
  38574. }
  38575. p3.subtractToRef(p2, this._edge);
  38576. p2.subtractToRef(this.basePoint, this._baseToVertex);
  38577. edgeSquaredLength = this._edge.lengthSquared();
  38578. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  38579. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  38580. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  38581. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  38582. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  38583. lowestRoot = getLowestRoot(a, b, c, t);
  38584. if (lowestRoot.found) {
  38585. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  38586. if (f >= 0.0 && f <= 1.0) {
  38587. t = lowestRoot.root;
  38588. found = true;
  38589. this._edge.scaleInPlace(f);
  38590. p2.addToRef(this._edge, this._collisionPoint);
  38591. }
  38592. }
  38593. p1.subtractToRef(p3, this._edge);
  38594. p3.subtractToRef(this.basePoint, this._baseToVertex);
  38595. edgeSquaredLength = this._edge.lengthSquared();
  38596. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  38597. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  38598. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  38599. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  38600. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  38601. lowestRoot = getLowestRoot(a, b, c, t);
  38602. if (lowestRoot.found) {
  38603. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  38604. if (f >= 0.0 && f <= 1.0) {
  38605. t = lowestRoot.root;
  38606. found = true;
  38607. this._edge.scaleInPlace(f);
  38608. p3.addToRef(this._edge, this._collisionPoint);
  38609. }
  38610. }
  38611. }
  38612. if (found) {
  38613. var distToCollision = t * this.velocity.length();
  38614. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  38615. if (!this.intersectionPoint) {
  38616. this.intersectionPoint = this._collisionPoint.clone();
  38617. }
  38618. else {
  38619. this.intersectionPoint.copyFrom(this._collisionPoint);
  38620. }
  38621. this.nearestDistance = distToCollision;
  38622. this.collisionFound = true;
  38623. }
  38624. }
  38625. };
  38626. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  38627. for (var i = indexStart; i < indexEnd; i += 3) {
  38628. var p1 = pts[indices[i] - decal];
  38629. var p2 = pts[indices[i + 1] - decal];
  38630. var p3 = pts[indices[i + 2] - decal];
  38631. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  38632. }
  38633. };
  38634. Collider.prototype._getResponse = function (pos, vel) {
  38635. pos.addToRef(vel, this._destinationPoint);
  38636. vel.scaleInPlace((this.nearestDistance / vel.length()));
  38637. this.basePoint.addToRef(vel, pos);
  38638. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  38639. this._slidePlaneNormal.normalize();
  38640. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  38641. pos.addInPlace(this._displacementVector);
  38642. this.intersectionPoint.addInPlace(this._displacementVector);
  38643. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  38644. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  38645. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  38646. };
  38647. return Collider;
  38648. }());
  38649. BABYLON.Collider = Collider;
  38650. })(BABYLON || (BABYLON = {}));
  38651. //# sourceMappingURL=babylon.collider.js.map
  38652. var BABYLON;
  38653. (function (BABYLON) {
  38654. //WebWorker code will be inserted to this variable.
  38655. BABYLON.CollisionWorker = "";
  38656. var WorkerTaskType;
  38657. (function (WorkerTaskType) {
  38658. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  38659. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  38660. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  38661. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  38662. var WorkerReplyType;
  38663. (function (WorkerReplyType) {
  38664. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  38665. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  38666. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  38667. var CollisionCoordinatorWorker = (function () {
  38668. function CollisionCoordinatorWorker() {
  38669. var _this = this;
  38670. this._scaledPosition = BABYLON.Vector3.Zero();
  38671. this._scaledVelocity = BABYLON.Vector3.Zero();
  38672. this.onMeshUpdated = function (mesh) {
  38673. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  38674. };
  38675. this.onGeometryUpdated = function (geometry) {
  38676. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  38677. };
  38678. this._afterRender = function () {
  38679. if (!_this._init)
  38680. return;
  38681. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  38682. return;
  38683. }
  38684. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  38685. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  38686. if (_this._runningUpdated > 4) {
  38687. return;
  38688. }
  38689. ++_this._runningUpdated;
  38690. var payload = {
  38691. updatedMeshes: _this._addUpdateMeshesList,
  38692. updatedGeometries: _this._addUpdateGeometriesList,
  38693. removedGeometries: _this._toRemoveGeometryArray,
  38694. removedMeshes: _this._toRemoveMeshesArray
  38695. };
  38696. var message = {
  38697. payload: payload,
  38698. taskType: WorkerTaskType.UPDATE
  38699. };
  38700. var serializable = [];
  38701. for (var id in payload.updatedGeometries) {
  38702. if (payload.updatedGeometries.hasOwnProperty(id)) {
  38703. //prepare transferables
  38704. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  38705. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  38706. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  38707. }
  38708. }
  38709. _this._worker.postMessage(message, serializable);
  38710. _this._addUpdateMeshesList = {};
  38711. _this._addUpdateGeometriesList = {};
  38712. _this._toRemoveGeometryArray = [];
  38713. _this._toRemoveMeshesArray = [];
  38714. };
  38715. this._onMessageFromWorker = function (e) {
  38716. var returnData = e.data;
  38717. if (returnData.error != WorkerReplyType.SUCCESS) {
  38718. //TODO what errors can be returned from the worker?
  38719. BABYLON.Tools.Warn("error returned from worker!");
  38720. return;
  38721. }
  38722. switch (returnData.taskType) {
  38723. case WorkerTaskType.INIT:
  38724. _this._init = true;
  38725. //Update the worked with ALL of the scene's current state
  38726. _this._scene.meshes.forEach(function (mesh) {
  38727. _this.onMeshAdded(mesh);
  38728. });
  38729. _this._scene.getGeometries().forEach(function (geometry) {
  38730. _this.onGeometryAdded(geometry);
  38731. });
  38732. break;
  38733. case WorkerTaskType.UPDATE:
  38734. _this._runningUpdated--;
  38735. break;
  38736. case WorkerTaskType.COLLIDE:
  38737. _this._runningCollisionTask = false;
  38738. var returnPayload = returnData.payload;
  38739. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  38740. return;
  38741. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  38742. //cleanup
  38743. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  38744. break;
  38745. }
  38746. };
  38747. this._collisionsCallbackArray = [];
  38748. this._init = false;
  38749. this._runningUpdated = 0;
  38750. this._runningCollisionTask = false;
  38751. this._addUpdateMeshesList = {};
  38752. this._addUpdateGeometriesList = {};
  38753. this._toRemoveGeometryArray = [];
  38754. this._toRemoveMeshesArray = [];
  38755. }
  38756. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  38757. if (!this._init)
  38758. return;
  38759. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  38760. return;
  38761. position.divideToRef(collider.radius, this._scaledPosition);
  38762. velocity.divideToRef(collider.radius, this._scaledVelocity);
  38763. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  38764. var payload = {
  38765. collider: {
  38766. position: this._scaledPosition.asArray(),
  38767. velocity: this._scaledVelocity.asArray(),
  38768. radius: collider.radius.asArray()
  38769. },
  38770. collisionId: collisionIndex,
  38771. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  38772. maximumRetry: maximumRetry
  38773. };
  38774. var message = {
  38775. payload: payload,
  38776. taskType: WorkerTaskType.COLLIDE
  38777. };
  38778. this._worker.postMessage(message);
  38779. };
  38780. CollisionCoordinatorWorker.prototype.init = function (scene) {
  38781. this._scene = scene;
  38782. this._scene.registerAfterRender(this._afterRender);
  38783. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  38784. this._worker = new Worker(workerUrl);
  38785. this._worker.onmessage = this._onMessageFromWorker;
  38786. var message = {
  38787. payload: {},
  38788. taskType: WorkerTaskType.INIT
  38789. };
  38790. this._worker.postMessage(message);
  38791. };
  38792. CollisionCoordinatorWorker.prototype.destroy = function () {
  38793. this._scene.unregisterAfterRender(this._afterRender);
  38794. this._worker.terminate();
  38795. };
  38796. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  38797. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  38798. this.onMeshUpdated(mesh);
  38799. };
  38800. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  38801. this._toRemoveMeshesArray.push(mesh.uniqueId);
  38802. };
  38803. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  38804. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  38805. geometry.onGeometryUpdated = this.onGeometryUpdated;
  38806. this.onGeometryUpdated(geometry);
  38807. };
  38808. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  38809. this._toRemoveGeometryArray.push(geometry.id);
  38810. };
  38811. return CollisionCoordinatorWorker;
  38812. }());
  38813. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  38814. var submeshes = [];
  38815. if (mesh.subMeshes) {
  38816. submeshes = mesh.subMeshes.map(function (sm, idx) {
  38817. return {
  38818. position: idx,
  38819. verticesStart: sm.verticesStart,
  38820. verticesCount: sm.verticesCount,
  38821. indexStart: sm.indexStart,
  38822. indexCount: sm.indexCount,
  38823. hasMaterial: !!sm.getMaterial(),
  38824. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  38825. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  38826. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  38827. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  38828. };
  38829. });
  38830. }
  38831. var geometryId = null;
  38832. if (mesh instanceof BABYLON.Mesh) {
  38833. geometryId = mesh.geometry ? mesh.geometry.id : null;
  38834. }
  38835. else if (mesh instanceof BABYLON.InstancedMesh) {
  38836. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  38837. }
  38838. return {
  38839. uniqueId: mesh.uniqueId,
  38840. id: mesh.id,
  38841. name: mesh.name,
  38842. geometryId: geometryId,
  38843. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  38844. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  38845. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  38846. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  38847. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  38848. subMeshes: submeshes,
  38849. checkCollisions: mesh.checkCollisions
  38850. };
  38851. };
  38852. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  38853. return {
  38854. id: geometry.id,
  38855. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  38856. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  38857. indices: new Uint32Array(geometry.getIndices() || []),
  38858. };
  38859. };
  38860. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  38861. var CollisionCoordinatorLegacy = (function () {
  38862. function CollisionCoordinatorLegacy() {
  38863. this._scaledPosition = BABYLON.Vector3.Zero();
  38864. this._scaledVelocity = BABYLON.Vector3.Zero();
  38865. this._finalPosition = BABYLON.Vector3.Zero();
  38866. }
  38867. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  38868. position.divideToRef(collider.radius, this._scaledPosition);
  38869. velocity.divideToRef(collider.radius, this._scaledVelocity);
  38870. collider.collidedMesh = null;
  38871. collider.retry = 0;
  38872. collider.initialVelocity = this._scaledVelocity;
  38873. collider.initialPosition = this._scaledPosition;
  38874. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  38875. this._finalPosition.multiplyInPlace(collider.radius);
  38876. //run the callback
  38877. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  38878. };
  38879. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  38880. this._scene = scene;
  38881. };
  38882. CollisionCoordinatorLegacy.prototype.destroy = function () {
  38883. //Legacy need no destruction method.
  38884. };
  38885. //No update in legacy mode
  38886. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  38887. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  38888. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  38889. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  38890. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  38891. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  38892. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  38893. if (excludedMesh === void 0) { excludedMesh = null; }
  38894. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  38895. if (collider.retry >= maximumRetry) {
  38896. finalPosition.copyFrom(position);
  38897. return;
  38898. }
  38899. // Check if this is a mesh else camera or -1
  38900. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  38901. collider._initialize(position, velocity, closeDistance);
  38902. // Check all meshes
  38903. for (var index = 0; index < this._scene.meshes.length; index++) {
  38904. var mesh = this._scene.meshes[index];
  38905. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  38906. mesh._checkCollision(collider);
  38907. }
  38908. }
  38909. if (!collider.collisionFound) {
  38910. position.addToRef(velocity, finalPosition);
  38911. return;
  38912. }
  38913. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  38914. collider._getResponse(position, velocity);
  38915. }
  38916. if (velocity.length() <= closeDistance) {
  38917. finalPosition.copyFrom(position);
  38918. return;
  38919. }
  38920. collider.retry++;
  38921. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  38922. };
  38923. return CollisionCoordinatorLegacy;
  38924. }());
  38925. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  38926. })(BABYLON || (BABYLON = {}));
  38927. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  38928. var BABYLON;
  38929. (function (BABYLON) {
  38930. var Particle = (function () {
  38931. function Particle() {
  38932. this.position = BABYLON.Vector3.Zero();
  38933. this.direction = BABYLON.Vector3.Zero();
  38934. this.color = new BABYLON.Color4(0, 0, 0, 0);
  38935. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  38936. this.lifeTime = 1.0;
  38937. this.age = 0;
  38938. this.size = 0;
  38939. this.angle = 0;
  38940. this.angularSpeed = 0;
  38941. }
  38942. Particle.prototype.copyTo = function (other) {
  38943. other.position.copyFrom(this.position);
  38944. other.direction.copyFrom(this.direction);
  38945. other.color.copyFrom(this.color);
  38946. other.colorStep.copyFrom(this.colorStep);
  38947. other.lifeTime = this.lifeTime;
  38948. other.age = this.age;
  38949. other.size = this.size;
  38950. other.angle = this.angle;
  38951. other.angularSpeed = this.angularSpeed;
  38952. };
  38953. return Particle;
  38954. }());
  38955. BABYLON.Particle = Particle;
  38956. })(BABYLON || (BABYLON = {}));
  38957. //# sourceMappingURL=babylon.particle.js.map
  38958. var BABYLON;
  38959. (function (BABYLON) {
  38960. var randomNumber = function (min, max) {
  38961. if (min === max) {
  38962. return (min);
  38963. }
  38964. var random = Math.random();
  38965. return ((random * (max - min)) + min);
  38966. };
  38967. var ParticleSystem = (function () {
  38968. function ParticleSystem(name, capacity, scene, customEffect) {
  38969. var _this = this;
  38970. this.name = name;
  38971. // Members
  38972. this.animations = [];
  38973. this.renderingGroupId = 0;
  38974. this.emitter = null;
  38975. this.emitRate = 10;
  38976. this.manualEmitCount = -1;
  38977. this.updateSpeed = 0.01;
  38978. this.targetStopDuration = 0;
  38979. this.disposeOnStop = false;
  38980. this.minEmitPower = 1;
  38981. this.maxEmitPower = 1;
  38982. this.minLifeTime = 1;
  38983. this.maxLifeTime = 1;
  38984. this.minSize = 1;
  38985. this.maxSize = 1;
  38986. this.minAngularSpeed = 0;
  38987. this.maxAngularSpeed = 0;
  38988. this.layerMask = 0x0FFFFFFF;
  38989. this.customShader = null;
  38990. this.preventAutoStart = false;
  38991. /**
  38992. * An event triggered when the system is disposed.
  38993. * @type {BABYLON.Observable}
  38994. */
  38995. this.onDisposeObservable = new BABYLON.Observable();
  38996. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  38997. this.forceDepthWrite = false;
  38998. this.gravity = BABYLON.Vector3.Zero();
  38999. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  39000. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  39001. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  39002. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39003. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39004. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39005. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  39006. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39007. this.particles = new Array();
  39008. this._stockParticles = new Array();
  39009. this._newPartsExcess = 0;
  39010. this._vertexBuffers = {};
  39011. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  39012. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  39013. this._scaledDirection = BABYLON.Vector3.Zero();
  39014. this._scaledGravity = BABYLON.Vector3.Zero();
  39015. this._currentRenderId = -1;
  39016. this._started = false;
  39017. this._stopped = false;
  39018. this._actualFrame = 0;
  39019. this.id = name;
  39020. this._capacity = capacity;
  39021. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  39022. this._customEffect = customEffect;
  39023. scene.particleSystems.push(this);
  39024. var indices = [];
  39025. var index = 0;
  39026. for (var count = 0; count < capacity; count++) {
  39027. indices.push(index);
  39028. indices.push(index + 1);
  39029. indices.push(index + 2);
  39030. indices.push(index);
  39031. indices.push(index + 2);
  39032. indices.push(index + 3);
  39033. index += 4;
  39034. }
  39035. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39036. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  39037. this._vertexData = new Float32Array(capacity * 11 * 4);
  39038. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  39039. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  39040. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  39041. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  39042. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39043. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39044. this._vertexBuffers["options"] = options;
  39045. // Default behaviors
  39046. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  39047. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  39048. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  39049. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  39050. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  39051. };
  39052. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  39053. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  39054. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  39055. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  39056. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  39057. };
  39058. this.updateFunction = function (particles) {
  39059. for (var index = 0; index < particles.length; index++) {
  39060. var particle = particles[index];
  39061. particle.age += _this._scaledUpdateSpeed;
  39062. if (particle.age >= particle.lifeTime) {
  39063. _this.recycleParticle(particle);
  39064. index--;
  39065. continue;
  39066. }
  39067. else {
  39068. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  39069. particle.color.addInPlace(_this._scaledColorStep);
  39070. if (particle.color.a < 0)
  39071. particle.color.a = 0;
  39072. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  39073. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  39074. particle.position.addInPlace(_this._scaledDirection);
  39075. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  39076. particle.direction.addInPlace(_this._scaledGravity);
  39077. }
  39078. }
  39079. };
  39080. }
  39081. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  39082. set: function (callback) {
  39083. if (this._onDisposeObserver) {
  39084. this.onDisposeObservable.remove(this._onDisposeObserver);
  39085. }
  39086. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39087. },
  39088. enumerable: true,
  39089. configurable: true
  39090. });
  39091. ParticleSystem.prototype.recycleParticle = function (particle) {
  39092. var lastParticle = this.particles.pop();
  39093. if (lastParticle !== particle) {
  39094. lastParticle.copyTo(particle);
  39095. this._stockParticles.push(lastParticle);
  39096. }
  39097. };
  39098. ParticleSystem.prototype.getCapacity = function () {
  39099. return this._capacity;
  39100. };
  39101. ParticleSystem.prototype.isAlive = function () {
  39102. return this._alive;
  39103. };
  39104. ParticleSystem.prototype.isStarted = function () {
  39105. return this._started;
  39106. };
  39107. ParticleSystem.prototype.start = function () {
  39108. this._started = true;
  39109. this._stopped = false;
  39110. this._actualFrame = 0;
  39111. };
  39112. ParticleSystem.prototype.stop = function () {
  39113. this._stopped = true;
  39114. };
  39115. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  39116. var offset = index * 11;
  39117. this._vertexData[offset] = particle.position.x;
  39118. this._vertexData[offset + 1] = particle.position.y;
  39119. this._vertexData[offset + 2] = particle.position.z;
  39120. this._vertexData[offset + 3] = particle.color.r;
  39121. this._vertexData[offset + 4] = particle.color.g;
  39122. this._vertexData[offset + 5] = particle.color.b;
  39123. this._vertexData[offset + 6] = particle.color.a;
  39124. this._vertexData[offset + 7] = particle.angle;
  39125. this._vertexData[offset + 8] = particle.size;
  39126. this._vertexData[offset + 9] = offsetX;
  39127. this._vertexData[offset + 10] = offsetY;
  39128. };
  39129. ParticleSystem.prototype._update = function (newParticles) {
  39130. // Update current
  39131. this._alive = this.particles.length > 0;
  39132. this.updateFunction(this.particles);
  39133. // Add new ones
  39134. var worldMatrix;
  39135. if (this.emitter.position) {
  39136. var emitterMesh = this.emitter;
  39137. worldMatrix = emitterMesh.getWorldMatrix();
  39138. }
  39139. else {
  39140. var emitterPosition = this.emitter;
  39141. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  39142. }
  39143. var particle;
  39144. for (var index = 0; index < newParticles; index++) {
  39145. if (this.particles.length === this._capacity) {
  39146. break;
  39147. }
  39148. if (this._stockParticles.length !== 0) {
  39149. particle = this._stockParticles.pop();
  39150. particle.age = 0;
  39151. }
  39152. else {
  39153. particle = new BABYLON.Particle();
  39154. }
  39155. this.particles.push(particle);
  39156. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  39157. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  39158. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  39159. particle.size = randomNumber(this.minSize, this.maxSize);
  39160. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  39161. this.startPositionFunction(worldMatrix, particle.position, particle);
  39162. var step = randomNumber(0, 1.0);
  39163. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  39164. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  39165. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  39166. }
  39167. };
  39168. ParticleSystem.prototype._getEffect = function () {
  39169. if (this._customEffect) {
  39170. return this._customEffect;
  39171. }
  39172. ;
  39173. var defines = [];
  39174. if (this._scene.clipPlane) {
  39175. defines.push("#define CLIPPLANE");
  39176. }
  39177. // Effect
  39178. var join = defines.join("\n");
  39179. if (this._cachedDefines !== join) {
  39180. this._cachedDefines = join;
  39181. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  39182. }
  39183. return this._effect;
  39184. };
  39185. ParticleSystem.prototype.animate = function () {
  39186. if (!this._started)
  39187. return;
  39188. var effect = this._getEffect();
  39189. // Check
  39190. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  39191. return;
  39192. if (this._currentRenderId === this._scene.getRenderId()) {
  39193. return;
  39194. }
  39195. this._currentRenderId = this._scene.getRenderId();
  39196. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  39197. // determine the number of particles we need to create
  39198. var newParticles;
  39199. if (this.manualEmitCount > -1) {
  39200. newParticles = this.manualEmitCount;
  39201. this._newPartsExcess = 0;
  39202. this.manualEmitCount = 0;
  39203. }
  39204. else {
  39205. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  39206. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  39207. }
  39208. if (this._newPartsExcess > 1.0) {
  39209. newParticles += this._newPartsExcess >> 0;
  39210. this._newPartsExcess -= this._newPartsExcess >> 0;
  39211. }
  39212. this._alive = false;
  39213. if (!this._stopped) {
  39214. this._actualFrame += this._scaledUpdateSpeed;
  39215. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  39216. this.stop();
  39217. }
  39218. else {
  39219. newParticles = 0;
  39220. }
  39221. this._update(newParticles);
  39222. // Stopped?
  39223. if (this._stopped) {
  39224. if (!this._alive) {
  39225. this._started = false;
  39226. if (this.disposeOnStop) {
  39227. this._scene._toBeDisposed.push(this);
  39228. }
  39229. }
  39230. }
  39231. // Update VBO
  39232. var offset = 0;
  39233. for (var index = 0; index < this.particles.length; index++) {
  39234. var particle = this.particles[index];
  39235. this._appendParticleVertex(offset++, particle, 0, 0);
  39236. this._appendParticleVertex(offset++, particle, 1, 0);
  39237. this._appendParticleVertex(offset++, particle, 1, 1);
  39238. this._appendParticleVertex(offset++, particle, 0, 1);
  39239. }
  39240. this._vertexBuffer.update(this._vertexData);
  39241. };
  39242. ParticleSystem.prototype.render = function () {
  39243. var effect = this._getEffect();
  39244. // Check
  39245. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  39246. return 0;
  39247. var engine = this._scene.getEngine();
  39248. // Render
  39249. engine.enableEffect(effect);
  39250. engine.setState(false);
  39251. var viewMatrix = this._scene.getViewMatrix();
  39252. effect.setTexture("diffuseSampler", this.particleTexture);
  39253. effect.setMatrix("view", viewMatrix);
  39254. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39255. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  39256. if (this._scene.clipPlane) {
  39257. var clipPlane = this._scene.clipPlane;
  39258. var invView = viewMatrix.clone();
  39259. invView.invert();
  39260. effect.setMatrix("invView", invView);
  39261. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39262. }
  39263. // VBOs
  39264. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39265. // Draw order
  39266. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  39267. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  39268. }
  39269. else {
  39270. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39271. }
  39272. if (this.forceDepthWrite) {
  39273. engine.setDepthWrite(true);
  39274. }
  39275. engine.draw(true, 0, this.particles.length * 6);
  39276. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39277. return this.particles.length;
  39278. };
  39279. ParticleSystem.prototype.dispose = function () {
  39280. if (this._vertexBuffer) {
  39281. this._vertexBuffer.dispose();
  39282. this._vertexBuffer = null;
  39283. }
  39284. if (this._indexBuffer) {
  39285. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39286. this._indexBuffer = null;
  39287. }
  39288. if (this.particleTexture) {
  39289. this.particleTexture.dispose();
  39290. this.particleTexture = null;
  39291. }
  39292. // Remove from scene
  39293. var index = this._scene.particleSystems.indexOf(this);
  39294. if (index > -1) {
  39295. this._scene.particleSystems.splice(index, 1);
  39296. }
  39297. // Callback
  39298. this.onDisposeObservable.notifyObservers(this);
  39299. this.onDisposeObservable.clear();
  39300. };
  39301. // Clone
  39302. ParticleSystem.prototype.clone = function (name, newEmitter) {
  39303. var custom = null;
  39304. var program = null;
  39305. if (this.customShader != null) {
  39306. program = this.customShader;
  39307. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  39308. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  39309. }
  39310. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  39311. result.customShader = program;
  39312. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  39313. if (newEmitter === undefined) {
  39314. newEmitter = this.emitter;
  39315. }
  39316. result.emitter = newEmitter;
  39317. if (this.particleTexture) {
  39318. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  39319. }
  39320. if (!this.preventAutoStart) {
  39321. result.start();
  39322. }
  39323. return result;
  39324. };
  39325. ParticleSystem.prototype.serialize = function () {
  39326. var serializationObject = {};
  39327. serializationObject.name = this.name;
  39328. serializationObject.id = this.id;
  39329. // Emitter
  39330. if (this.emitter.position) {
  39331. var emitterMesh = this.emitter;
  39332. serializationObject.emitterId = emitterMesh.id;
  39333. }
  39334. else {
  39335. var emitterPosition = this.emitter;
  39336. serializationObject.emitter = emitterPosition.asArray();
  39337. }
  39338. serializationObject.capacity = this.getCapacity();
  39339. if (this.particleTexture) {
  39340. serializationObject.textureName = this.particleTexture.name;
  39341. }
  39342. // Animations
  39343. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  39344. // Particle system
  39345. serializationObject.minAngularSpeed = this.minAngularSpeed;
  39346. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  39347. serializationObject.minSize = this.minSize;
  39348. serializationObject.maxSize = this.maxSize;
  39349. serializationObject.minEmitPower = this.minEmitPower;
  39350. serializationObject.maxEmitPower = this.maxEmitPower;
  39351. serializationObject.minLifeTime = this.minLifeTime;
  39352. serializationObject.maxLifeTime = this.maxLifeTime;
  39353. serializationObject.emitRate = this.emitRate;
  39354. serializationObject.minEmitBox = this.minEmitBox.asArray();
  39355. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  39356. serializationObject.gravity = this.gravity.asArray();
  39357. serializationObject.direction1 = this.direction1.asArray();
  39358. serializationObject.direction2 = this.direction2.asArray();
  39359. serializationObject.color1 = this.color1.asArray();
  39360. serializationObject.color2 = this.color2.asArray();
  39361. serializationObject.colorDead = this.colorDead.asArray();
  39362. serializationObject.updateSpeed = this.updateSpeed;
  39363. serializationObject.targetStopDuration = this.targetStopDuration;
  39364. serializationObject.textureMask = this.textureMask.asArray();
  39365. serializationObject.blendMode = this.blendMode;
  39366. serializationObject.customShader = this.customShader;
  39367. serializationObject.preventAutoStart = this.preventAutoStart;
  39368. return serializationObject;
  39369. };
  39370. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  39371. var name = parsedParticleSystem.name;
  39372. var custom = null;
  39373. var program = null;
  39374. if (parsedParticleSystem.customShader) {
  39375. program = parsedParticleSystem.customShader;
  39376. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  39377. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  39378. }
  39379. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  39380. particleSystem.customShader = program;
  39381. if (parsedParticleSystem.id) {
  39382. particleSystem.id = parsedParticleSystem.id;
  39383. }
  39384. // Auto start
  39385. if (parsedParticleSystem.preventAutoStart) {
  39386. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  39387. }
  39388. // Texture
  39389. if (parsedParticleSystem.textureName) {
  39390. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  39391. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  39392. }
  39393. // Emitter
  39394. if (parsedParticleSystem.emitterId) {
  39395. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  39396. }
  39397. else {
  39398. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  39399. }
  39400. // Animations
  39401. if (parsedParticleSystem.animations) {
  39402. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  39403. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  39404. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  39405. }
  39406. }
  39407. if (parsedParticleSystem.autoAnimate) {
  39408. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  39409. }
  39410. // Particle system
  39411. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  39412. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  39413. particleSystem.minSize = parsedParticleSystem.minSize;
  39414. particleSystem.maxSize = parsedParticleSystem.maxSize;
  39415. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  39416. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  39417. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  39418. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  39419. particleSystem.emitRate = parsedParticleSystem.emitRate;
  39420. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  39421. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  39422. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  39423. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  39424. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  39425. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  39426. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  39427. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  39428. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  39429. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  39430. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  39431. particleSystem.blendMode = parsedParticleSystem.blendMode;
  39432. if (!particleSystem.preventAutoStart) {
  39433. particleSystem.start();
  39434. }
  39435. return particleSystem;
  39436. };
  39437. return ParticleSystem;
  39438. }());
  39439. // Statics
  39440. ParticleSystem.BLENDMODE_ONEONE = 0;
  39441. ParticleSystem.BLENDMODE_STANDARD = 1;
  39442. BABYLON.ParticleSystem = ParticleSystem;
  39443. })(BABYLON || (BABYLON = {}));
  39444. //# sourceMappingURL=babylon.particleSystem.js.map
  39445. var BABYLON;
  39446. (function (BABYLON) {
  39447. var SolidParticle = (function () {
  39448. /**
  39449. * Creates a Solid Particle object.
  39450. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  39451. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  39452. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  39453. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  39454. * `shapeId` (integer) is the model shape identifier in the SPS.
  39455. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  39456. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  39457. */
  39458. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  39459. this.idx = 0; // particle global index
  39460. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  39461. this.position = BABYLON.Vector3.Zero(); // position
  39462. this.rotation = BABYLON.Vector3.Zero(); // rotation
  39463. this.scaling = BABYLON.Vector3.One(); // scaling
  39464. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  39465. this.velocity = BABYLON.Vector3.Zero(); // velocity
  39466. this.alive = true; // alive
  39467. this.isVisible = true; // visibility
  39468. this._pos = 0; // index of this particle in the global "positions" array
  39469. this.shapeId = 0; // model shape id
  39470. this.idxInShape = 0; // index of the particle in its shape id
  39471. this.idx = particleIndex;
  39472. this._pos = positionIndex;
  39473. this._model = model;
  39474. this.shapeId = shapeId;
  39475. this.idxInShape = idxInShape;
  39476. this._sps = sps;
  39477. if (modelBoundingInfo) {
  39478. this._modelBoundingInfo = modelBoundingInfo;
  39479. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  39480. }
  39481. }
  39482. Object.defineProperty(SolidParticle.prototype, "scale", {
  39483. /**
  39484. * legacy support, changed scale to scaling
  39485. */
  39486. get: function () {
  39487. return this.scaling;
  39488. },
  39489. set: function (scale) {
  39490. this.scaling = scale;
  39491. },
  39492. enumerable: true,
  39493. configurable: true
  39494. });
  39495. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  39496. /**
  39497. * legacy support, changed quaternion to rotationQuaternion
  39498. */
  39499. get: function () {
  39500. return this.rotationQuaternion;
  39501. },
  39502. set: function (q) {
  39503. this.rotationQuaternion = q;
  39504. },
  39505. enumerable: true,
  39506. configurable: true
  39507. });
  39508. /**
  39509. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  39510. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  39511. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  39512. */
  39513. SolidParticle.prototype.intersectsMesh = function (target) {
  39514. if (!this._boundingInfo || !target._boundingInfo) {
  39515. return false;
  39516. }
  39517. if (this._sps._bSphereOnly) {
  39518. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  39519. }
  39520. return this._boundingInfo.intersects(target._boundingInfo, false);
  39521. };
  39522. return SolidParticle;
  39523. }());
  39524. BABYLON.SolidParticle = SolidParticle;
  39525. var ModelShape = (function () {
  39526. /**
  39527. * 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.
  39528. * SPS internal tool, don't use it manually.
  39529. */
  39530. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  39531. this.shapeID = id;
  39532. this._shape = shape;
  39533. this._shapeUV = shapeUV;
  39534. this._positionFunction = posFunction;
  39535. this._vertexFunction = vtxFunction;
  39536. }
  39537. return ModelShape;
  39538. }());
  39539. BABYLON.ModelShape = ModelShape;
  39540. })(BABYLON || (BABYLON = {}));
  39541. //# sourceMappingURL=babylon.solidParticle.js.map
  39542. var BABYLON;
  39543. (function (BABYLON) {
  39544. /**
  39545. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  39546. */
  39547. var SolidParticleSystem = (function () {
  39548. /**
  39549. * Creates a SPS (Solid Particle System) object.
  39550. * `name` (String) is the SPS name, this will be the underlying mesh name.
  39551. * `scene` (Scene) is the scene in which the SPS is added.
  39552. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  39553. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  39554. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  39555. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  39556. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  39557. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  39558. */
  39559. function SolidParticleSystem(name, scene, options) {
  39560. // public members
  39561. /**
  39562. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  39563. * Example : var p = SPS.particles[i];
  39564. */
  39565. this.particles = new Array();
  39566. /**
  39567. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  39568. */
  39569. this.nbParticles = 0;
  39570. /**
  39571. * If the particles must ever face the camera (default false). Useful for planar particles.
  39572. */
  39573. this.billboard = false;
  39574. /**
  39575. * Recompute normals when adding a shape
  39576. */
  39577. this.recomputeNormals = true;
  39578. /**
  39579. * This a counter ofr your own usage. It's not set by any SPS functions.
  39580. */
  39581. this.counter = 0;
  39582. /**
  39583. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  39584. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  39585. */
  39586. this.vars = {};
  39587. this._positions = new Array();
  39588. this._indices = new Array();
  39589. this._normals = new Array();
  39590. this._colors = new Array();
  39591. this._uvs = new Array();
  39592. this._index = 0; // indices index
  39593. this._updatable = true;
  39594. this._pickable = false;
  39595. this._isVisibilityBoxLocked = false;
  39596. this._alwaysVisible = false;
  39597. this._shapeCounter = 0;
  39598. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  39599. this._color = new BABYLON.Color4(0, 0, 0, 0);
  39600. this._computeParticleColor = true;
  39601. this._computeParticleTexture = true;
  39602. this._computeParticleRotation = true;
  39603. this._computeParticleVertex = false;
  39604. this._computeBoundingBox = false;
  39605. this._cam_axisZ = BABYLON.Vector3.Zero();
  39606. this._cam_axisY = BABYLON.Vector3.Zero();
  39607. this._cam_axisX = BABYLON.Vector3.Zero();
  39608. this._axisX = BABYLON.Axis.X;
  39609. this._axisY = BABYLON.Axis.Y;
  39610. this._axisZ = BABYLON.Axis.Z;
  39611. this._camDir = BABYLON.Vector3.Zero();
  39612. this._rotMatrix = new BABYLON.Matrix();
  39613. this._invertMatrix = new BABYLON.Matrix();
  39614. this._rotated = BABYLON.Vector3.Zero();
  39615. this._quaternion = new BABYLON.Quaternion();
  39616. this._vertex = BABYLON.Vector3.Zero();
  39617. this._normal = BABYLON.Vector3.Zero();
  39618. this._yaw = 0.0;
  39619. this._pitch = 0.0;
  39620. this._roll = 0.0;
  39621. this._halfroll = 0.0;
  39622. this._halfpitch = 0.0;
  39623. this._halfyaw = 0.0;
  39624. this._sinRoll = 0.0;
  39625. this._cosRoll = 0.0;
  39626. this._sinPitch = 0.0;
  39627. this._cosPitch = 0.0;
  39628. this._sinYaw = 0.0;
  39629. this._cosYaw = 0.0;
  39630. this._w = 0.0;
  39631. this._mustUnrotateFixedNormals = false;
  39632. this._minimum = BABYLON.Tmp.Vector3[0];
  39633. this._maximum = BABYLON.Tmp.Vector3[1];
  39634. this._scale = BABYLON.Tmp.Vector3[2];
  39635. this._translation = BABYLON.Tmp.Vector3[3];
  39636. this._minBbox = BABYLON.Tmp.Vector3[4];
  39637. this._maxBbox = BABYLON.Tmp.Vector3[5];
  39638. this._particlesIntersect = false;
  39639. this._bSphereOnly = false;
  39640. this._bSphereRadiusFactor = 1.0;
  39641. this.name = name;
  39642. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  39643. this._camera = scene.activeCamera;
  39644. this._pickable = options ? options.isPickable : false;
  39645. this._particlesIntersect = options ? options.particleIntersection : false;
  39646. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  39647. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  39648. if (options && options.updatable) {
  39649. this._updatable = options.updatable;
  39650. }
  39651. else {
  39652. this._updatable = true;
  39653. }
  39654. if (this._pickable) {
  39655. this.pickedParticles = [];
  39656. }
  39657. }
  39658. /**
  39659. * Builds the SPS underlying mesh. Returns a standard Mesh.
  39660. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  39661. */
  39662. SolidParticleSystem.prototype.buildMesh = function () {
  39663. if (this.nbParticles === 0) {
  39664. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  39665. this.addShape(triangle, 1);
  39666. triangle.dispose();
  39667. }
  39668. this._positions32 = new Float32Array(this._positions);
  39669. this._uvs32 = new Float32Array(this._uvs);
  39670. this._colors32 = new Float32Array(this._colors);
  39671. if (this.recomputeNormals) {
  39672. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  39673. }
  39674. this._normals32 = new Float32Array(this._normals);
  39675. this._fixedNormal32 = new Float32Array(this._normals);
  39676. if (this._mustUnrotateFixedNormals) {
  39677. this._unrotateFixedNormals();
  39678. }
  39679. var vertexData = new BABYLON.VertexData();
  39680. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  39681. vertexData.indices = this._indices;
  39682. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  39683. if (this._uvs32) {
  39684. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  39685. ;
  39686. }
  39687. if (this._colors32) {
  39688. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  39689. }
  39690. var mesh = new BABYLON.Mesh(this.name, this._scene);
  39691. vertexData.applyToMesh(mesh, this._updatable);
  39692. this.mesh = mesh;
  39693. this.mesh.isPickable = this._pickable;
  39694. // free memory
  39695. this._positions = null;
  39696. this._normals = null;
  39697. this._uvs = null;
  39698. this._colors = null;
  39699. if (!this._updatable) {
  39700. this.particles.length = 0;
  39701. }
  39702. return mesh;
  39703. };
  39704. /**
  39705. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  39706. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  39707. * Thus the particles generated from `digest()` have their property `position` set yet.
  39708. * `mesh` ( Mesh ) is the mesh to be digested
  39709. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  39710. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  39711. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  39712. */
  39713. SolidParticleSystem.prototype.digest = function (mesh, options) {
  39714. var size = (options && options.facetNb) || 1;
  39715. var number = (options && options.number);
  39716. var delta = (options && options.delta) || 0;
  39717. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39718. var meshInd = mesh.getIndices();
  39719. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39720. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39721. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39722. var f = 0; // facet counter
  39723. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  39724. // compute size from number
  39725. if (number) {
  39726. number = (number > totalFacets) ? totalFacets : number;
  39727. size = Math.round(totalFacets / number);
  39728. delta = 0;
  39729. }
  39730. else {
  39731. size = (size > totalFacets) ? totalFacets : size;
  39732. }
  39733. var facetPos = []; // submesh positions
  39734. var facetInd = []; // submesh indices
  39735. var facetUV = []; // submesh UV
  39736. var facetCol = []; // submesh colors
  39737. var barycenter = BABYLON.Tmp.Vector3[0];
  39738. var rand;
  39739. var sizeO = size;
  39740. while (f < totalFacets) {
  39741. size = sizeO + Math.floor((1 + delta) * Math.random());
  39742. if (f > totalFacets - size) {
  39743. size = totalFacets - f;
  39744. }
  39745. // reset temp arrays
  39746. facetPos.length = 0;
  39747. facetInd.length = 0;
  39748. facetUV.length = 0;
  39749. facetCol.length = 0;
  39750. // iterate over "size" facets
  39751. var fi = 0;
  39752. for (var j = f * 3; j < (f + size) * 3; j++) {
  39753. facetInd.push(fi);
  39754. var i = meshInd[j];
  39755. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  39756. if (meshUV) {
  39757. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  39758. }
  39759. if (meshCol) {
  39760. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  39761. }
  39762. fi++;
  39763. }
  39764. // create a model shape for each single particle
  39765. var idx = this.nbParticles;
  39766. var shape = this._posToShape(facetPos);
  39767. var shapeUV = this._uvsToShapeUV(facetUV);
  39768. // compute the barycenter of the shape
  39769. var v;
  39770. for (v = 0; v < shape.length; v++) {
  39771. barycenter.addInPlace(shape[v]);
  39772. }
  39773. barycenter.scaleInPlace(1 / shape.length);
  39774. // shift the shape from its barycenter to the origin
  39775. for (v = 0; v < shape.length; v++) {
  39776. shape[v].subtractInPlace(barycenter);
  39777. }
  39778. var bInfo;
  39779. if (this._particlesIntersect) {
  39780. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  39781. }
  39782. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  39783. // add the particle in the SPS
  39784. var currentPos = this._positions.length;
  39785. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  39786. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  39787. // initialize the particle position
  39788. this.particles[this.nbParticles].position.addInPlace(barycenter);
  39789. this._index += shape.length;
  39790. idx++;
  39791. this.nbParticles++;
  39792. this._shapeCounter++;
  39793. f += size;
  39794. }
  39795. return this;
  39796. };
  39797. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  39798. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  39799. var index = 0;
  39800. var idx = 0;
  39801. for (var p = 0; p < this.particles.length; p++) {
  39802. this._particle = this.particles[p];
  39803. this._shape = this._particle._model._shape;
  39804. if (this._particle.rotationQuaternion) {
  39805. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  39806. }
  39807. else {
  39808. this._yaw = this._particle.rotation.y;
  39809. this._pitch = this._particle.rotation.x;
  39810. this._roll = this._particle.rotation.z;
  39811. this._quaternionRotationYPR();
  39812. }
  39813. this._quaternionToRotationMatrix();
  39814. this._rotMatrix.invertToRef(this._invertMatrix);
  39815. for (var pt = 0; pt < this._shape.length; pt++) {
  39816. idx = index + pt * 3;
  39817. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  39818. this._fixedNormal32[idx] = this._normal.x;
  39819. this._fixedNormal32[idx + 1] = this._normal.y;
  39820. this._fixedNormal32[idx + 2] = this._normal.z;
  39821. }
  39822. index = idx + 3;
  39823. }
  39824. };
  39825. //reset copy
  39826. SolidParticleSystem.prototype._resetCopy = function () {
  39827. this._copy.position.x = 0;
  39828. this._copy.position.y = 0;
  39829. this._copy.position.z = 0;
  39830. this._copy.rotation.x = 0;
  39831. this._copy.rotation.y = 0;
  39832. this._copy.rotation.z = 0;
  39833. this._copy.rotationQuaternion = null;
  39834. this._copy.scaling.x = 1;
  39835. this._copy.scaling.y = 1;
  39836. this._copy.scaling.z = 1;
  39837. this._copy.uvs.x = 0;
  39838. this._copy.uvs.y = 0;
  39839. this._copy.uvs.z = 1;
  39840. this._copy.uvs.w = 1;
  39841. this._copy.color = null;
  39842. };
  39843. // _meshBuilder : inserts the shape model in the global SPS mesh
  39844. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  39845. var i;
  39846. var u = 0;
  39847. var c = 0;
  39848. var n = 0;
  39849. this._resetCopy();
  39850. if (options && options.positionFunction) {
  39851. options.positionFunction(this._copy, idx, idxInShape);
  39852. this._mustUnrotateFixedNormals = true;
  39853. }
  39854. if (this._copy.rotationQuaternion) {
  39855. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  39856. }
  39857. else {
  39858. this._yaw = this._copy.rotation.y;
  39859. this._pitch = this._copy.rotation.x;
  39860. this._roll = this._copy.rotation.z;
  39861. this._quaternionRotationYPR();
  39862. }
  39863. this._quaternionToRotationMatrix();
  39864. for (i = 0; i < shape.length; i++) {
  39865. this._vertex.x = shape[i].x;
  39866. this._vertex.y = shape[i].y;
  39867. this._vertex.z = shape[i].z;
  39868. if (options && options.vertexFunction) {
  39869. options.vertexFunction(this._copy, this._vertex, i);
  39870. }
  39871. this._vertex.x *= this._copy.scaling.x;
  39872. this._vertex.y *= this._copy.scaling.y;
  39873. this._vertex.z *= this._copy.scaling.z;
  39874. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  39875. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  39876. if (meshUV) {
  39877. 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);
  39878. u += 2;
  39879. }
  39880. if (this._copy.color) {
  39881. this._color = this._copy.color;
  39882. }
  39883. else if (meshCol && meshCol[c] !== undefined) {
  39884. this._color.r = meshCol[c];
  39885. this._color.g = meshCol[c + 1];
  39886. this._color.b = meshCol[c + 2];
  39887. this._color.a = meshCol[c + 3];
  39888. }
  39889. else {
  39890. this._color.r = 1;
  39891. this._color.g = 1;
  39892. this._color.b = 1;
  39893. this._color.a = 1;
  39894. }
  39895. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  39896. c += 4;
  39897. if (!this.recomputeNormals && meshNor) {
  39898. this._normal.x = meshNor[n];
  39899. this._normal.y = meshNor[n + 1];
  39900. this._normal.z = meshNor[n + 2];
  39901. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  39902. normals.push(this._normal.x, this._normal.y, this._normal.z);
  39903. n += 3;
  39904. }
  39905. }
  39906. for (i = 0; i < meshInd.length; i++) {
  39907. indices.push(p + meshInd[i]);
  39908. }
  39909. if (this._pickable) {
  39910. var nbfaces = meshInd.length / 3;
  39911. for (i = 0; i < nbfaces; i++) {
  39912. this.pickedParticles.push({ idx: idx, faceId: i });
  39913. }
  39914. }
  39915. return this._copy;
  39916. };
  39917. // returns a shape array from positions array
  39918. SolidParticleSystem.prototype._posToShape = function (positions) {
  39919. var shape = [];
  39920. for (var i = 0; i < positions.length; i += 3) {
  39921. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  39922. }
  39923. return shape;
  39924. };
  39925. // returns a shapeUV array from a Vector4 uvs
  39926. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  39927. var shapeUV = [];
  39928. if (uvs) {
  39929. for (var i = 0; i < uvs.length; i++)
  39930. shapeUV.push(uvs[i]);
  39931. }
  39932. return shapeUV;
  39933. };
  39934. // adds a new particle object in the particles array
  39935. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  39936. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  39937. this.particles.push(sp);
  39938. return sp;
  39939. };
  39940. /**
  39941. * Adds some particles to the SPS from the model shape. Returns the shape id.
  39942. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  39943. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  39944. * `nb` (positive integer) the number of particles to be created from this model
  39945. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  39946. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  39947. */
  39948. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  39949. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39950. var meshInd = mesh.getIndices();
  39951. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39952. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39953. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39954. var bbInfo;
  39955. if (this._particlesIntersect) {
  39956. bbInfo = mesh.getBoundingInfo();
  39957. }
  39958. var shape = this._posToShape(meshPos);
  39959. var shapeUV = this._uvsToShapeUV(meshUV);
  39960. var posfunc = options ? options.positionFunction : null;
  39961. var vtxfunc = options ? options.vertexFunction : null;
  39962. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  39963. // particles
  39964. var sp;
  39965. var currentCopy;
  39966. var idx = this.nbParticles;
  39967. for (var i = 0; i < nb; i++) {
  39968. var currentPos = this._positions.length;
  39969. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  39970. if (this._updatable) {
  39971. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  39972. sp.position.copyFrom(currentCopy.position);
  39973. sp.rotation.copyFrom(currentCopy.rotation);
  39974. if (currentCopy.rotationQuaternion) {
  39975. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  39976. }
  39977. if (currentCopy.color) {
  39978. sp.color.copyFrom(currentCopy.color);
  39979. }
  39980. sp.scaling.copyFrom(currentCopy.scaling);
  39981. sp.uvs.copyFrom(currentCopy.uvs);
  39982. }
  39983. this._index += shape.length;
  39984. idx++;
  39985. }
  39986. this.nbParticles += nb;
  39987. this._shapeCounter++;
  39988. return this._shapeCounter - 1;
  39989. };
  39990. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  39991. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  39992. this._resetCopy();
  39993. if (particle._model._positionFunction) {
  39994. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  39995. }
  39996. if (this._copy.rotationQuaternion) {
  39997. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  39998. }
  39999. else {
  40000. this._yaw = this._copy.rotation.y;
  40001. this._pitch = this._copy.rotation.x;
  40002. this._roll = this._copy.rotation.z;
  40003. this._quaternionRotationYPR();
  40004. }
  40005. this._quaternionToRotationMatrix();
  40006. this._shape = particle._model._shape;
  40007. for (var pt = 0; pt < this._shape.length; pt++) {
  40008. this._vertex.x = this._shape[pt].x;
  40009. this._vertex.y = this._shape[pt].y;
  40010. this._vertex.z = this._shape[pt].z;
  40011. if (particle._model._vertexFunction) {
  40012. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  40013. }
  40014. this._vertex.x *= this._copy.scaling.x;
  40015. this._vertex.y *= this._copy.scaling.y;
  40016. this._vertex.z *= this._copy.scaling.z;
  40017. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40018. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  40019. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  40020. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  40021. }
  40022. particle.position.x = 0.0;
  40023. particle.position.y = 0.0;
  40024. particle.position.z = 0.0;
  40025. particle.rotation.x = 0.0;
  40026. particle.rotation.y = 0.0;
  40027. particle.rotation.z = 0.0;
  40028. particle.rotationQuaternion = null;
  40029. particle.scaling.x = 1.0;
  40030. particle.scaling.y = 1.0;
  40031. particle.scaling.z = 1.0;
  40032. };
  40033. /**
  40034. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  40035. * Returns the SPS.
  40036. */
  40037. SolidParticleSystem.prototype.rebuildMesh = function () {
  40038. for (var p = 0; p < this.particles.length; p++) {
  40039. this._rebuildParticle(this.particles[p]);
  40040. }
  40041. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40042. return this;
  40043. };
  40044. /**
  40045. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  40046. * This method calls `updateParticle()` for each particle of the SPS.
  40047. * For an animated SPS, it is usually called within the render loop.
  40048. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  40049. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  40050. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  40051. * Returns the SPS.
  40052. */
  40053. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  40054. if (start === void 0) { start = 0; }
  40055. if (end === void 0) { end = this.nbParticles - 1; }
  40056. if (update === void 0) { update = true; }
  40057. if (!this._updatable) {
  40058. return;
  40059. }
  40060. // custom beforeUpdate
  40061. this.beforeUpdateParticles(start, end, update);
  40062. this._cam_axisX.x = 1.0;
  40063. this._cam_axisX.y = 0.0;
  40064. this._cam_axisX.z = 0.0;
  40065. this._cam_axisY.x = 0.0;
  40066. this._cam_axisY.y = 1.0;
  40067. this._cam_axisY.z = 0.0;
  40068. this._cam_axisZ.x = 0.0;
  40069. this._cam_axisZ.y = 0.0;
  40070. this._cam_axisZ.z = 1.0;
  40071. // if the particles will always face the camera
  40072. if (this.billboard) {
  40073. this.mesh.computeWorldMatrix(true);
  40074. // compute the camera position and un-rotate it by the current mesh rotation
  40075. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  40076. this._quaternionToRotationMatrix();
  40077. this._rotMatrix.invertToRef(this._invertMatrix);
  40078. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  40079. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  40080. this._cam_axisZ.normalize();
  40081. // same for camera up vector extracted from the cam view matrix
  40082. var view = this._camera.getViewMatrix(true);
  40083. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  40084. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  40085. this._cam_axisY.normalize();
  40086. this._cam_axisX.normalize();
  40087. }
  40088. }
  40089. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  40090. var idx = 0; // current position index in the global array positions32
  40091. var index = 0; // position start index in the global array positions32 of the current particle
  40092. var colidx = 0; // current color index in the global array colors32
  40093. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  40094. var uvidx = 0; // current uv index in the global array uvs32
  40095. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  40096. var pt = 0; // current index in the particle model shape
  40097. if (this.mesh.isFacetDataEnabled) {
  40098. this._computeBoundingBox = true;
  40099. }
  40100. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  40101. if (this._computeBoundingBox) {
  40102. if (start == 0 && end == this.nbParticles - 1) {
  40103. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  40104. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  40105. }
  40106. else {
  40107. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  40108. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  40109. }
  40110. }
  40111. // particle loop
  40112. index = this.particles[start]._pos;
  40113. var vpos = (index / 3) | 0;
  40114. colorIndex = vpos * 4;
  40115. uvIndex = vpos * 2;
  40116. for (var p = start; p <= end; p++) {
  40117. this._particle = this.particles[p];
  40118. this._shape = this._particle._model._shape;
  40119. this._shapeUV = this._particle._model._shapeUV;
  40120. // call to custom user function to update the particle properties
  40121. this.updateParticle(this._particle);
  40122. if (this._particle.isVisible) {
  40123. // particle rotation matrix
  40124. if (this.billboard) {
  40125. this._particle.rotation.x = 0.0;
  40126. this._particle.rotation.y = 0.0;
  40127. }
  40128. if (this._computeParticleRotation || this.billboard) {
  40129. if (this._particle.rotationQuaternion) {
  40130. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  40131. }
  40132. else {
  40133. this._yaw = this._particle.rotation.y;
  40134. this._pitch = this._particle.rotation.x;
  40135. this._roll = this._particle.rotation.z;
  40136. this._quaternionRotationYPR();
  40137. }
  40138. this._quaternionToRotationMatrix();
  40139. }
  40140. // particle vertex loop
  40141. for (pt = 0; pt < this._shape.length; pt++) {
  40142. idx = index + pt * 3;
  40143. colidx = colorIndex + pt * 4;
  40144. uvidx = uvIndex + pt * 2;
  40145. this._vertex.x = this._shape[pt].x;
  40146. this._vertex.y = this._shape[pt].y;
  40147. this._vertex.z = this._shape[pt].z;
  40148. if (this._computeParticleVertex) {
  40149. this.updateParticleVertex(this._particle, this._vertex, pt);
  40150. }
  40151. // positions
  40152. this._vertex.x *= this._particle.scaling.x;
  40153. this._vertex.y *= this._particle.scaling.y;
  40154. this._vertex.z *= this._particle.scaling.z;
  40155. 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];
  40156. 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;
  40157. 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;
  40158. 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;
  40159. 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;
  40160. 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;
  40161. 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;
  40162. if (this._computeBoundingBox) {
  40163. if (this._positions32[idx] < this._minimum.x) {
  40164. this._minimum.x = this._positions32[idx];
  40165. }
  40166. if (this._positions32[idx] > this._maximum.x) {
  40167. this._maximum.x = this._positions32[idx];
  40168. }
  40169. if (this._positions32[idx + 1] < this._minimum.y) {
  40170. this._minimum.y = this._positions32[idx + 1];
  40171. }
  40172. if (this._positions32[idx + 1] > this._maximum.y) {
  40173. this._maximum.y = this._positions32[idx + 1];
  40174. }
  40175. if (this._positions32[idx + 2] < this._minimum.z) {
  40176. this._minimum.z = this._positions32[idx + 2];
  40177. }
  40178. if (this._positions32[idx + 2] > this._maximum.z) {
  40179. this._maximum.z = this._positions32[idx + 2];
  40180. }
  40181. }
  40182. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  40183. if (!this._computeParticleVertex) {
  40184. this._normal.x = this._fixedNormal32[idx];
  40185. this._normal.y = this._fixedNormal32[idx + 1];
  40186. this._normal.z = this._fixedNormal32[idx + 2];
  40187. 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]);
  40188. 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]);
  40189. 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]);
  40190. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  40191. 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;
  40192. 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;
  40193. }
  40194. if (this._computeParticleColor) {
  40195. this._colors32[colidx] = this._particle.color.r;
  40196. this._colors32[colidx + 1] = this._particle.color.g;
  40197. this._colors32[colidx + 2] = this._particle.color.b;
  40198. this._colors32[colidx + 3] = this._particle.color.a;
  40199. }
  40200. if (this._computeParticleTexture) {
  40201. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40202. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40203. }
  40204. }
  40205. }
  40206. else {
  40207. for (pt = 0; pt < this._shape.length; pt++) {
  40208. idx = index + pt * 3;
  40209. colidx = colorIndex + pt * 4;
  40210. uvidx = uvIndex + pt * 2;
  40211. this._positions32[idx] = this._camera.globalPosition.x;
  40212. this._positions32[idx + 1] = this._camera.globalPosition.y;
  40213. this._positions32[idx + 2] = this._camera.globalPosition.z;
  40214. this._normals32[idx] = 0.0;
  40215. this._normals32[idx + 1] = 0.0;
  40216. this._normals32[idx + 2] = 0.0;
  40217. if (this._computeParticleColor) {
  40218. this._colors32[colidx] = this._particle.color.r;
  40219. this._colors32[colidx + 1] = this._particle.color.g;
  40220. this._colors32[colidx + 2] = this._particle.color.b;
  40221. this._colors32[colidx + 3] = this._particle.color.a;
  40222. }
  40223. if (this._computeParticleTexture) {
  40224. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40225. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40226. }
  40227. }
  40228. }
  40229. // if the particle intersections must be computed : update the bbInfo
  40230. if (this._particlesIntersect) {
  40231. var bInfo = this._particle._boundingInfo;
  40232. var bBox = bInfo.boundingBox;
  40233. var bSphere = bInfo.boundingSphere;
  40234. if (!this._bSphereOnly) {
  40235. // place, scale and rotate the particle bbox within the SPS local system, then update it
  40236. for (var b = 0; b < bBox.vectors.length; b++) {
  40237. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  40238. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  40239. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  40240. 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];
  40241. 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;
  40242. 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;
  40243. 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;
  40244. 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;
  40245. 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;
  40246. 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;
  40247. }
  40248. bBox._update(this.mesh._worldMatrix);
  40249. }
  40250. // place and scale the particle bouding sphere in the SPS local system, then update it
  40251. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  40252. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  40253. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  40254. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  40255. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  40256. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  40257. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  40258. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  40259. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  40260. 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));
  40261. bSphere._update(this.mesh._worldMatrix);
  40262. }
  40263. // increment indexes for the next particle
  40264. index = idx + 3;
  40265. colorIndex = colidx + 4;
  40266. uvIndex = uvidx + 2;
  40267. }
  40268. // if the VBO must be updated
  40269. if (update) {
  40270. if (this._computeParticleColor) {
  40271. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  40272. }
  40273. if (this._computeParticleTexture) {
  40274. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  40275. }
  40276. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40277. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  40278. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  40279. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  40280. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  40281. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  40282. for (var i = 0; i < this._normals32.length; i++) {
  40283. this._fixedNormal32[i] = this._normals32[i];
  40284. }
  40285. }
  40286. if (!this.mesh.areNormalsFrozen) {
  40287. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  40288. }
  40289. }
  40290. }
  40291. if (this._computeBoundingBox) {
  40292. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  40293. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  40294. }
  40295. this.afterUpdateParticles(start, end, update);
  40296. return this;
  40297. };
  40298. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  40299. this._halfroll = this._roll * 0.5;
  40300. this._halfpitch = this._pitch * 0.5;
  40301. this._halfyaw = this._yaw * 0.5;
  40302. this._sinRoll = Math.sin(this._halfroll);
  40303. this._cosRoll = Math.cos(this._halfroll);
  40304. this._sinPitch = Math.sin(this._halfpitch);
  40305. this._cosPitch = Math.cos(this._halfpitch);
  40306. this._sinYaw = Math.sin(this._halfyaw);
  40307. this._cosYaw = Math.cos(this._halfyaw);
  40308. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  40309. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  40310. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  40311. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  40312. };
  40313. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  40314. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  40315. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  40316. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  40317. this._rotMatrix.m[3] = 0;
  40318. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  40319. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  40320. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  40321. this._rotMatrix.m[7] = 0;
  40322. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  40323. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  40324. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  40325. this._rotMatrix.m[11] = 0;
  40326. this._rotMatrix.m[12] = 0;
  40327. this._rotMatrix.m[13] = 0;
  40328. this._rotMatrix.m[14] = 0;
  40329. this._rotMatrix.m[15] = 1.0;
  40330. };
  40331. /**
  40332. * Disposes the SPS.
  40333. * Returns nothing.
  40334. */
  40335. SolidParticleSystem.prototype.dispose = function () {
  40336. this.mesh.dispose();
  40337. this.vars = null;
  40338. // drop references to internal big arrays for the GC
  40339. this._positions = null;
  40340. this._indices = null;
  40341. this._normals = null;
  40342. this._uvs = null;
  40343. this._colors = null;
  40344. this._positions32 = null;
  40345. this._normals32 = null;
  40346. this._fixedNormal32 = null;
  40347. this._uvs32 = null;
  40348. this._colors32 = null;
  40349. this.pickedParticles = null;
  40350. };
  40351. /**
  40352. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  40353. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40354. * Returns the SPS.
  40355. */
  40356. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  40357. if (!this._isVisibilityBoxLocked) {
  40358. this.mesh.refreshBoundingInfo();
  40359. }
  40360. return this;
  40361. };
  40362. /**
  40363. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  40364. * @param size the size (float) of the visibility box
  40365. * note : this doesn't lock the SPS mesh bounding box.
  40366. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40367. */
  40368. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  40369. var vis = size / 2;
  40370. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  40371. };
  40372. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  40373. // getter and setter
  40374. get: function () {
  40375. return this._alwaysVisible;
  40376. },
  40377. /**
  40378. * Sets the SPS as always visible or not
  40379. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40380. */
  40381. set: function (val) {
  40382. this._alwaysVisible = val;
  40383. this.mesh.alwaysSelectAsActiveMesh = val;
  40384. },
  40385. enumerable: true,
  40386. configurable: true
  40387. });
  40388. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  40389. get: function () {
  40390. return this._isVisibilityBoxLocked;
  40391. },
  40392. /**
  40393. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  40394. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40395. */
  40396. set: function (val) {
  40397. this._isVisibilityBoxLocked = val;
  40398. this.mesh.getBoundingInfo().isLocked = val;
  40399. },
  40400. enumerable: true,
  40401. configurable: true
  40402. });
  40403. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  40404. // getters
  40405. get: function () {
  40406. return this._computeParticleRotation;
  40407. },
  40408. // Optimizer setters
  40409. /**
  40410. * Tells to `setParticles()` to compute the particle rotations or not.
  40411. * Default value : true. The SPS is faster when it's set to false.
  40412. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  40413. */
  40414. set: function (val) {
  40415. this._computeParticleRotation = val;
  40416. },
  40417. enumerable: true,
  40418. configurable: true
  40419. });
  40420. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  40421. get: function () {
  40422. return this._computeParticleColor;
  40423. },
  40424. /**
  40425. * Tells to `setParticles()` to compute the particle colors or not.
  40426. * Default value : true. The SPS is faster when it's set to false.
  40427. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  40428. */
  40429. set: function (val) {
  40430. this._computeParticleColor = val;
  40431. },
  40432. enumerable: true,
  40433. configurable: true
  40434. });
  40435. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  40436. get: function () {
  40437. return this._computeParticleTexture;
  40438. },
  40439. /**
  40440. * Tells to `setParticles()` to compute the particle textures or not.
  40441. * Default value : true. The SPS is faster when it's set to false.
  40442. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  40443. */
  40444. set: function (val) {
  40445. this._computeParticleTexture = val;
  40446. },
  40447. enumerable: true,
  40448. configurable: true
  40449. });
  40450. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  40451. get: function () {
  40452. return this._computeParticleVertex;
  40453. },
  40454. /**
  40455. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  40456. * Default value : false. The SPS is faster when it's set to false.
  40457. * Note : the particle custom vertex positions aren't stored values.
  40458. */
  40459. set: function (val) {
  40460. this._computeParticleVertex = val;
  40461. },
  40462. enumerable: true,
  40463. configurable: true
  40464. });
  40465. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  40466. get: function () {
  40467. return this._computeBoundingBox;
  40468. },
  40469. /**
  40470. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  40471. */
  40472. set: function (val) {
  40473. this._computeBoundingBox = val;
  40474. },
  40475. enumerable: true,
  40476. configurable: true
  40477. });
  40478. // =======================================================================
  40479. // Particle behavior logic
  40480. // these following methods may be overwritten by the user to fit his needs
  40481. /**
  40482. * This function does nothing. It may be overwritten to set all the particle first values.
  40483. * The SPS doesn't call this function, you may have to call it by your own.
  40484. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  40485. */
  40486. SolidParticleSystem.prototype.initParticles = function () {
  40487. };
  40488. /**
  40489. * This function does nothing. It may be overwritten to recycle a particle.
  40490. * The SPS doesn't call this function, you may have to call it by your own.
  40491. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  40492. */
  40493. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  40494. return particle;
  40495. };
  40496. /**
  40497. * Updates a particle : this function should be overwritten by the user.
  40498. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  40499. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  40500. * ex : just set a particle position or velocity and recycle conditions
  40501. */
  40502. SolidParticleSystem.prototype.updateParticle = function (particle) {
  40503. return particle;
  40504. };
  40505. /**
  40506. * Updates a vertex of a particle : it can be overwritten by the user.
  40507. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  40508. * @param particle the current particle
  40509. * @param vertex the current index of the current particle
  40510. * @param pt the index of the current vertex in the particle shape
  40511. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  40512. * ex : just set a vertex particle position
  40513. */
  40514. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  40515. return vertex;
  40516. };
  40517. /**
  40518. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  40519. * This does nothing and may be overwritten by the user.
  40520. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40521. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40522. * @param update the boolean update value actually passed to setParticles()
  40523. */
  40524. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  40525. };
  40526. /**
  40527. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  40528. * This will be passed three parameters.
  40529. * This does nothing and may be overwritten by the user.
  40530. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40531. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40532. * @param update the boolean update value actually passed to setParticles()
  40533. */
  40534. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  40535. };
  40536. return SolidParticleSystem;
  40537. }());
  40538. BABYLON.SolidParticleSystem = SolidParticleSystem;
  40539. })(BABYLON || (BABYLON = {}));
  40540. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  40541. /// <reference path="babylon.mesh.ts" />
  40542. var BABYLON;
  40543. (function (BABYLON) {
  40544. var GroundMesh = (function (_super) {
  40545. __extends(GroundMesh, _super);
  40546. function GroundMesh(name, scene) {
  40547. var _this = _super.call(this, name, scene) || this;
  40548. _this.generateOctree = false;
  40549. _this._worldInverse = new BABYLON.Matrix();
  40550. return _this;
  40551. }
  40552. GroundMesh.prototype.getClassName = function () {
  40553. return "GroundMesh";
  40554. };
  40555. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  40556. get: function () {
  40557. return Math.min(this._subdivisionsX, this._subdivisionsY);
  40558. },
  40559. enumerable: true,
  40560. configurable: true
  40561. });
  40562. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  40563. get: function () {
  40564. return this._subdivisionsX;
  40565. },
  40566. enumerable: true,
  40567. configurable: true
  40568. });
  40569. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  40570. get: function () {
  40571. return this._subdivisionsY;
  40572. },
  40573. enumerable: true,
  40574. configurable: true
  40575. });
  40576. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  40577. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  40578. this._subdivisionsX = chunksCount;
  40579. this._subdivisionsY = chunksCount;
  40580. this.subdivide(chunksCount);
  40581. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  40582. };
  40583. /**
  40584. * Returns a height (y) value in the Worl system :
  40585. * the ground altitude at the coordinates (x, z) expressed in the World system.
  40586. * Returns the ground y position if (x, z) are outside the ground surface.
  40587. */
  40588. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  40589. var world = this.getWorldMatrix();
  40590. var invMat = BABYLON.Tmp.Matrix[5];
  40591. world.invertToRef(invMat);
  40592. var tmpVect = BABYLON.Tmp.Vector3[8];
  40593. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  40594. x = tmpVect.x;
  40595. z = tmpVect.z;
  40596. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40597. return this.position.y;
  40598. }
  40599. if (!this._heightQuads || this._heightQuads.length == 0) {
  40600. this._initHeightQuads();
  40601. this._computeHeightQuads();
  40602. }
  40603. var facet = this._getFacetAt(x, z);
  40604. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  40605. // return y in the World system
  40606. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  40607. return tmpVect.y;
  40608. };
  40609. /**
  40610. * Returns a normalized vector (Vector3) orthogonal to the ground
  40611. * at the ground coordinates (x, z) expressed in the World system.
  40612. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  40613. */
  40614. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  40615. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  40616. this.getNormalAtCoordinatesToRef(x, z, normal);
  40617. return normal;
  40618. };
  40619. /**
  40620. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  40621. * at the ground coordinates (x, z) expressed in the World system.
  40622. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  40623. * Returns the GroundMesh.
  40624. */
  40625. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  40626. var world = this.getWorldMatrix();
  40627. var tmpMat = BABYLON.Tmp.Matrix[5];
  40628. world.invertToRef(tmpMat);
  40629. var tmpVect = BABYLON.Tmp.Vector3[8];
  40630. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  40631. x = tmpVect.x;
  40632. z = tmpVect.z;
  40633. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40634. return this;
  40635. }
  40636. if (!this._heightQuads || this._heightQuads.length == 0) {
  40637. this._initHeightQuads();
  40638. this._computeHeightQuads();
  40639. }
  40640. var facet = this._getFacetAt(x, z);
  40641. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  40642. return this;
  40643. };
  40644. /**
  40645. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  40646. * if the ground has been updated.
  40647. * This can be used in the render loop.
  40648. * Returns the GroundMesh.
  40649. */
  40650. GroundMesh.prototype.updateCoordinateHeights = function () {
  40651. if (!this._heightQuads || this._heightQuads.length == 0) {
  40652. this._initHeightQuads();
  40653. }
  40654. this._computeHeightQuads();
  40655. return this;
  40656. };
  40657. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  40658. GroundMesh.prototype._getFacetAt = function (x, z) {
  40659. // retrieve col and row from x, z coordinates in the ground local system
  40660. var subdivisionsX = this._subdivisionsX;
  40661. var subdivisionsY = this._subdivisionsY;
  40662. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  40663. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  40664. var quad = this._heightQuads[row * this._subdivisionsX + col];
  40665. var facet;
  40666. if (z < quad.slope.x * x + quad.slope.y) {
  40667. facet = quad.facet1;
  40668. }
  40669. else {
  40670. facet = quad.facet2;
  40671. }
  40672. return facet;
  40673. };
  40674. // Creates and populates the heightMap array with "facet" elements :
  40675. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  40676. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40677. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40678. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40679. // Returns the GroundMesh.
  40680. GroundMesh.prototype._initHeightQuads = function () {
  40681. var subdivisionsX = this._subdivisionsX;
  40682. var subdivisionsY = this._subdivisionsY;
  40683. this._heightQuads = new Array();
  40684. for (var row = 0; row < subdivisionsY; row++) {
  40685. for (var col = 0; col < subdivisionsX; col++) {
  40686. 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) };
  40687. this._heightQuads[row * subdivisionsX + col] = quad;
  40688. }
  40689. }
  40690. return this;
  40691. };
  40692. // Compute each quad element values and update the the heightMap array :
  40693. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40694. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40695. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40696. // Returns the GroundMesh.
  40697. GroundMesh.prototype._computeHeightQuads = function () {
  40698. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40699. var v1 = BABYLON.Tmp.Vector3[3];
  40700. var v2 = BABYLON.Tmp.Vector3[2];
  40701. var v3 = BABYLON.Tmp.Vector3[1];
  40702. var v4 = BABYLON.Tmp.Vector3[0];
  40703. var v1v2 = BABYLON.Tmp.Vector3[4];
  40704. var v1v3 = BABYLON.Tmp.Vector3[5];
  40705. var v1v4 = BABYLON.Tmp.Vector3[6];
  40706. var norm1 = BABYLON.Tmp.Vector3[7];
  40707. var norm2 = BABYLON.Tmp.Vector3[8];
  40708. var i = 0;
  40709. var j = 0;
  40710. var k = 0;
  40711. var cd = 0; // 2D slope coefficient : z = cd * x + h
  40712. var h = 0;
  40713. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  40714. var d2 = 0;
  40715. var subdivisionsX = this._subdivisionsX;
  40716. var subdivisionsY = this._subdivisionsY;
  40717. for (var row = 0; row < subdivisionsY; row++) {
  40718. for (var col = 0; col < subdivisionsX; col++) {
  40719. i = col * 3;
  40720. j = row * (subdivisionsX + 1) * 3;
  40721. k = (row + 1) * (subdivisionsX + 1) * 3;
  40722. v1.x = positions[j + i];
  40723. v1.y = positions[j + i + 1];
  40724. v1.z = positions[j + i + 2];
  40725. v2.x = positions[j + i + 3];
  40726. v2.y = positions[j + i + 4];
  40727. v2.z = positions[j + i + 5];
  40728. v3.x = positions[k + i];
  40729. v3.y = positions[k + i + 1];
  40730. v3.z = positions[k + i + 2];
  40731. v4.x = positions[k + i + 3];
  40732. v4.y = positions[k + i + 4];
  40733. v4.z = positions[k + i + 5];
  40734. // 2D slope V1V4
  40735. cd = (v4.z - v1.z) / (v4.x - v1.x);
  40736. h = v1.z - cd * v1.x; // v1 belongs to the slope
  40737. // facet equations :
  40738. // we compute each facet normal vector
  40739. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  40740. // we compute the value d by applying the equation to v1 which belongs to the plane
  40741. // then we store the facet equation in a Vector4
  40742. v2.subtractToRef(v1, v1v2);
  40743. v3.subtractToRef(v1, v1v3);
  40744. v4.subtractToRef(v1, v1v4);
  40745. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  40746. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  40747. norm1.normalize();
  40748. norm2.normalize();
  40749. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  40750. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  40751. var quad = this._heightQuads[row * subdivisionsX + col];
  40752. quad.slope.copyFromFloats(cd, h);
  40753. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  40754. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  40755. }
  40756. }
  40757. return this;
  40758. };
  40759. GroundMesh.prototype.serialize = function (serializationObject) {
  40760. _super.prototype.serialize.call(this, serializationObject);
  40761. serializationObject.subdivisionsX = this._subdivisionsX;
  40762. serializationObject.subdivisionsY = this._subdivisionsY;
  40763. serializationObject.minX = this._minX;
  40764. serializationObject.maxX = this._maxX;
  40765. serializationObject.minZ = this._minZ;
  40766. serializationObject.maxZ = this._maxZ;
  40767. serializationObject.width = this._width;
  40768. serializationObject.height = this._height;
  40769. };
  40770. GroundMesh.Parse = function (parsedMesh, scene) {
  40771. var result = new GroundMesh(parsedMesh.name, scene);
  40772. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  40773. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  40774. result._minX = parsedMesh.minX;
  40775. result._maxX = parsedMesh.maxX;
  40776. result._minZ = parsedMesh.minZ;
  40777. result._maxZ = parsedMesh.maxZ;
  40778. result._width = parsedMesh.width;
  40779. result._height = parsedMesh.height;
  40780. return result;
  40781. };
  40782. return GroundMesh;
  40783. }(BABYLON.Mesh));
  40784. BABYLON.GroundMesh = GroundMesh;
  40785. })(BABYLON || (BABYLON = {}));
  40786. //# sourceMappingURL=babylon.groundMesh.js.map
  40787. var BABYLON;
  40788. (function (BABYLON) {
  40789. /**
  40790. * Creates an instance based on a source mesh.
  40791. */
  40792. var InstancedMesh = (function (_super) {
  40793. __extends(InstancedMesh, _super);
  40794. function InstancedMesh(name, source) {
  40795. var _this = _super.call(this, name, source.getScene()) || this;
  40796. source.instances.push(_this);
  40797. _this._sourceMesh = source;
  40798. _this.position.copyFrom(source.position);
  40799. _this.rotation.copyFrom(source.rotation);
  40800. _this.scaling.copyFrom(source.scaling);
  40801. if (source.rotationQuaternion) {
  40802. _this.rotationQuaternion = source.rotationQuaternion.clone();
  40803. }
  40804. _this.infiniteDistance = source.infiniteDistance;
  40805. _this.setPivotMatrix(source.getPivotMatrix());
  40806. _this.refreshBoundingInfo();
  40807. _this._syncSubMeshes();
  40808. return _this;
  40809. }
  40810. /**
  40811. * Returns the string "InstancedMesh".
  40812. */
  40813. InstancedMesh.prototype.getClassName = function () {
  40814. return "InstancedMesh";
  40815. };
  40816. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  40817. // Methods
  40818. get: function () {
  40819. return this._sourceMesh.receiveShadows;
  40820. },
  40821. enumerable: true,
  40822. configurable: true
  40823. });
  40824. Object.defineProperty(InstancedMesh.prototype, "material", {
  40825. get: function () {
  40826. return this._sourceMesh.material;
  40827. },
  40828. enumerable: true,
  40829. configurable: true
  40830. });
  40831. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  40832. get: function () {
  40833. return this._sourceMesh.visibility;
  40834. },
  40835. enumerable: true,
  40836. configurable: true
  40837. });
  40838. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  40839. get: function () {
  40840. return this._sourceMesh.skeleton;
  40841. },
  40842. enumerable: true,
  40843. configurable: true
  40844. });
  40845. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  40846. get: function () {
  40847. return this._sourceMesh.renderingGroupId;
  40848. },
  40849. enumerable: true,
  40850. configurable: true
  40851. });
  40852. /**
  40853. * Returns the total number of vertices (integer).
  40854. */
  40855. InstancedMesh.prototype.getTotalVertices = function () {
  40856. return this._sourceMesh.getTotalVertices();
  40857. };
  40858. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  40859. get: function () {
  40860. return this._sourceMesh;
  40861. },
  40862. enumerable: true,
  40863. configurable: true
  40864. });
  40865. /**
  40866. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  40867. */
  40868. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  40869. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  40870. };
  40871. /**
  40872. * Sets the vertex data of the mesh geometry for the requested `kind`.
  40873. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  40874. * The `data` are either a numeric array either a Float32Array.
  40875. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  40876. * 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).
  40877. * Note that a new underlying VertexBuffer object is created each call.
  40878. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  40879. *
  40880. * Possible `kind` values :
  40881. * - BABYLON.VertexBuffer.PositionKind
  40882. * - BABYLON.VertexBuffer.UVKind
  40883. * - BABYLON.VertexBuffer.UV2Kind
  40884. * - BABYLON.VertexBuffer.UV3Kind
  40885. * - BABYLON.VertexBuffer.UV4Kind
  40886. * - BABYLON.VertexBuffer.UV5Kind
  40887. * - BABYLON.VertexBuffer.UV6Kind
  40888. * - BABYLON.VertexBuffer.ColorKind
  40889. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40890. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40891. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40892. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40893. *
  40894. * Returns the Mesh.
  40895. */
  40896. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40897. if (this.sourceMesh) {
  40898. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  40899. }
  40900. return this.sourceMesh;
  40901. };
  40902. /**
  40903. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  40904. * If the mesh has no geometry, it is simply returned as it is.
  40905. * The `data` are either a numeric array either a Float32Array.
  40906. * No new underlying VertexBuffer object is created.
  40907. * 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.
  40908. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  40909. *
  40910. * Possible `kind` values :
  40911. * - BABYLON.VertexBuffer.PositionKind
  40912. * - BABYLON.VertexBuffer.UVKind
  40913. * - BABYLON.VertexBuffer.UV2Kind
  40914. * - BABYLON.VertexBuffer.UV3Kind
  40915. * - BABYLON.VertexBuffer.UV4Kind
  40916. * - BABYLON.VertexBuffer.UV5Kind
  40917. * - BABYLON.VertexBuffer.UV6Kind
  40918. * - BABYLON.VertexBuffer.ColorKind
  40919. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40920. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40921. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40922. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40923. *
  40924. * Returns the Mesh.
  40925. */
  40926. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  40927. if (this.sourceMesh) {
  40928. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  40929. }
  40930. return this.sourceMesh;
  40931. };
  40932. /**
  40933. * Sets the mesh indices.
  40934. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  40935. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  40936. * This method creates a new index buffer each call.
  40937. * Returns the Mesh.
  40938. */
  40939. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  40940. if (this.sourceMesh) {
  40941. this.sourceMesh.setIndices(indices, totalVertices);
  40942. }
  40943. return this.sourceMesh;
  40944. };
  40945. /**
  40946. * Boolean : True if the mesh owns the requested kind of data.
  40947. */
  40948. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  40949. return this._sourceMesh.isVerticesDataPresent(kind);
  40950. };
  40951. /**
  40952. * Returns an array of indices (IndicesArray).
  40953. */
  40954. InstancedMesh.prototype.getIndices = function () {
  40955. return this._sourceMesh.getIndices();
  40956. };
  40957. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  40958. get: function () {
  40959. return this._sourceMesh._positions;
  40960. },
  40961. enumerable: true,
  40962. configurable: true
  40963. });
  40964. /**
  40965. * Sets a new updated BoundingInfo to the mesh.
  40966. * Returns the mesh.
  40967. */
  40968. InstancedMesh.prototype.refreshBoundingInfo = function () {
  40969. var meshBB = this._sourceMesh.getBoundingInfo();
  40970. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  40971. this._updateBoundingInfo();
  40972. return this;
  40973. };
  40974. InstancedMesh.prototype._preActivate = function () {
  40975. if (this._currentLOD) {
  40976. this._currentLOD._preActivate();
  40977. }
  40978. return this;
  40979. };
  40980. InstancedMesh.prototype._activate = function (renderId) {
  40981. if (this._currentLOD) {
  40982. this._currentLOD._registerInstanceForRenderId(this, renderId);
  40983. }
  40984. return this;
  40985. };
  40986. /**
  40987. * Returns the current associated LOD AbstractMesh.
  40988. */
  40989. InstancedMesh.prototype.getLOD = function (camera) {
  40990. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  40991. if (this._currentLOD === this.sourceMesh) {
  40992. return this;
  40993. }
  40994. return this._currentLOD;
  40995. };
  40996. InstancedMesh.prototype._syncSubMeshes = function () {
  40997. this.releaseSubMeshes();
  40998. if (this._sourceMesh.subMeshes) {
  40999. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  41000. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  41001. }
  41002. }
  41003. return this;
  41004. };
  41005. InstancedMesh.prototype._generatePointsArray = function () {
  41006. return this._sourceMesh._generatePointsArray();
  41007. };
  41008. /**
  41009. * Creates a new InstancedMesh from the current mesh.
  41010. * - name (string) : the cloned mesh name
  41011. * - newParent (optional Node) : the optional Node to parent the clone to.
  41012. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  41013. *
  41014. * Returns the clone.
  41015. */
  41016. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41017. var result = this._sourceMesh.createInstance(name);
  41018. // Deep copy
  41019. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  41020. // Bounding info
  41021. this.refreshBoundingInfo();
  41022. // Parent
  41023. if (newParent) {
  41024. result.parent = newParent;
  41025. }
  41026. if (!doNotCloneChildren) {
  41027. // Children
  41028. for (var index = 0; index < this.getScene().meshes.length; index++) {
  41029. var mesh = this.getScene().meshes[index];
  41030. if (mesh.parent === this) {
  41031. mesh.clone(mesh.name, result);
  41032. }
  41033. }
  41034. }
  41035. result.computeWorldMatrix(true);
  41036. return result;
  41037. };
  41038. /**
  41039. * Disposes the InstancedMesh.
  41040. * Returns nothing.
  41041. */
  41042. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  41043. // Remove from mesh
  41044. var index = this._sourceMesh.instances.indexOf(this);
  41045. this._sourceMesh.instances.splice(index, 1);
  41046. _super.prototype.dispose.call(this, doNotRecurse);
  41047. };
  41048. return InstancedMesh;
  41049. }(BABYLON.AbstractMesh));
  41050. BABYLON.InstancedMesh = InstancedMesh;
  41051. })(BABYLON || (BABYLON = {}));
  41052. //# sourceMappingURL=babylon.instancedMesh.js.map
  41053. /// <reference path="babylon.mesh.ts" />
  41054. var BABYLON;
  41055. (function (BABYLON) {
  41056. var LinesMesh = (function (_super) {
  41057. __extends(LinesMesh, _super);
  41058. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  41059. if (parent === void 0) { parent = null; }
  41060. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  41061. _this.useVertexColor = useVertexColor;
  41062. _this.color = new BABYLON.Color3(1, 1, 1);
  41063. _this.alpha = 1;
  41064. if (source) {
  41065. _this.color = source.color.clone();
  41066. _this.alpha = source.alpha;
  41067. _this.useVertexColor = source.useVertexColor;
  41068. }
  41069. _this._intersectionThreshold = 0.1;
  41070. var options = {
  41071. attributes: [BABYLON.VertexBuffer.PositionKind],
  41072. uniforms: ["world", "viewProjection"],
  41073. needAlphaBlending: false,
  41074. };
  41075. if (!useVertexColor) {
  41076. options.uniforms.push("color");
  41077. options.needAlphaBlending = true;
  41078. }
  41079. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  41080. return _this;
  41081. }
  41082. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  41083. /**
  41084. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41085. * This margin is expressed in world space coordinates, so its value may vary.
  41086. * Default value is 0.1
  41087. * @returns the intersection Threshold value.
  41088. */
  41089. get: function () {
  41090. return this._intersectionThreshold;
  41091. },
  41092. /**
  41093. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41094. * This margin is expressed in world space coordinates, so its value may vary.
  41095. * @param value the new threshold to apply
  41096. */
  41097. set: function (value) {
  41098. if (this._intersectionThreshold === value) {
  41099. return;
  41100. }
  41101. this._intersectionThreshold = value;
  41102. if (this.geometry) {
  41103. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  41104. }
  41105. },
  41106. enumerable: true,
  41107. configurable: true
  41108. });
  41109. /**
  41110. * Returns the string "LineMesh"
  41111. */
  41112. LinesMesh.prototype.getClassName = function () {
  41113. return "LinesMesh";
  41114. };
  41115. Object.defineProperty(LinesMesh.prototype, "material", {
  41116. get: function () {
  41117. return this._colorShader;
  41118. },
  41119. enumerable: true,
  41120. configurable: true
  41121. });
  41122. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  41123. get: function () {
  41124. return false;
  41125. },
  41126. enumerable: true,
  41127. configurable: true
  41128. });
  41129. LinesMesh.prototype.createInstance = function (name) {
  41130. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  41131. return null;
  41132. };
  41133. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  41134. // VBOs
  41135. this._geometry._bind(this._colorShader.getEffect());
  41136. // Color
  41137. if (!this.useVertexColor) {
  41138. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  41139. }
  41140. return this;
  41141. };
  41142. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  41143. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  41144. return this;
  41145. }
  41146. var engine = this.getScene().getEngine();
  41147. // Draw order
  41148. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  41149. return this;
  41150. };
  41151. LinesMesh.prototype.dispose = function (doNotRecurse) {
  41152. this._colorShader.dispose();
  41153. _super.prototype.dispose.call(this, doNotRecurse);
  41154. };
  41155. /**
  41156. * Returns a new LineMesh object cloned from the current one.
  41157. */
  41158. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41159. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  41160. };
  41161. return LinesMesh;
  41162. }(BABYLON.Mesh));
  41163. BABYLON.LinesMesh = LinesMesh;
  41164. })(BABYLON || (BABYLON = {}));
  41165. //# sourceMappingURL=babylon.linesMesh.js.map
  41166. var BABYLON;
  41167. (function (BABYLON) {
  41168. var ShaderMaterial = (function (_super) {
  41169. __extends(ShaderMaterial, _super);
  41170. function ShaderMaterial(name, scene, shaderPath, options) {
  41171. var _this = _super.call(this, name, scene) || this;
  41172. _this._textures = {};
  41173. _this._textureArrays = {};
  41174. _this._floats = {};
  41175. _this._floatsArrays = {};
  41176. _this._colors3 = {};
  41177. _this._colors4 = {};
  41178. _this._vectors2 = {};
  41179. _this._vectors3 = {};
  41180. _this._vectors4 = {};
  41181. _this._matrices = {};
  41182. _this._matrices3x3 = {};
  41183. _this._matrices2x2 = {};
  41184. _this._vectors3Arrays = {};
  41185. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  41186. _this._shaderPath = shaderPath;
  41187. options.needAlphaBlending = options.needAlphaBlending || false;
  41188. options.needAlphaTesting = options.needAlphaTesting || false;
  41189. options.attributes = options.attributes || ["position", "normal", "uv"];
  41190. options.uniforms = options.uniforms || ["worldViewProjection"];
  41191. options.uniformBuffers = options.uniformBuffers || [];
  41192. options.samplers = options.samplers || [];
  41193. options.defines = options.defines || [];
  41194. _this._options = options;
  41195. return _this;
  41196. }
  41197. ShaderMaterial.prototype.getClassName = function () {
  41198. return "ShaderMaterial";
  41199. };
  41200. ShaderMaterial.prototype.needAlphaBlending = function () {
  41201. return this._options.needAlphaBlending;
  41202. };
  41203. ShaderMaterial.prototype.needAlphaTesting = function () {
  41204. return this._options.needAlphaTesting;
  41205. };
  41206. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  41207. if (this._options.uniforms.indexOf(uniformName) === -1) {
  41208. this._options.uniforms.push(uniformName);
  41209. }
  41210. };
  41211. ShaderMaterial.prototype.setTexture = function (name, texture) {
  41212. if (this._options.samplers.indexOf(name) === -1) {
  41213. this._options.samplers.push(name);
  41214. }
  41215. this._textures[name] = texture;
  41216. return this;
  41217. };
  41218. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  41219. if (this._options.samplers.indexOf(name) === -1) {
  41220. this._options.samplers.push(name);
  41221. }
  41222. this._checkUniform(name);
  41223. this._textureArrays[name] = textures;
  41224. return this;
  41225. };
  41226. ShaderMaterial.prototype.setFloat = function (name, value) {
  41227. this._checkUniform(name);
  41228. this._floats[name] = value;
  41229. return this;
  41230. };
  41231. ShaderMaterial.prototype.setFloats = function (name, value) {
  41232. this._checkUniform(name);
  41233. this._floatsArrays[name] = value;
  41234. return this;
  41235. };
  41236. ShaderMaterial.prototype.setColor3 = function (name, value) {
  41237. this._checkUniform(name);
  41238. this._colors3[name] = value;
  41239. return this;
  41240. };
  41241. ShaderMaterial.prototype.setColor4 = function (name, value) {
  41242. this._checkUniform(name);
  41243. this._colors4[name] = value;
  41244. return this;
  41245. };
  41246. ShaderMaterial.prototype.setVector2 = function (name, value) {
  41247. this._checkUniform(name);
  41248. this._vectors2[name] = value;
  41249. return this;
  41250. };
  41251. ShaderMaterial.prototype.setVector3 = function (name, value) {
  41252. this._checkUniform(name);
  41253. this._vectors3[name] = value;
  41254. return this;
  41255. };
  41256. ShaderMaterial.prototype.setVector4 = function (name, value) {
  41257. this._checkUniform(name);
  41258. this._vectors4[name] = value;
  41259. return this;
  41260. };
  41261. ShaderMaterial.prototype.setMatrix = function (name, value) {
  41262. this._checkUniform(name);
  41263. this._matrices[name] = value;
  41264. return this;
  41265. };
  41266. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  41267. this._checkUniform(name);
  41268. this._matrices3x3[name] = value;
  41269. return this;
  41270. };
  41271. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  41272. this._checkUniform(name);
  41273. this._matrices2x2[name] = value;
  41274. return this;
  41275. };
  41276. ShaderMaterial.prototype.setArray3 = function (name, value) {
  41277. this._checkUniform(name);
  41278. this._vectors3Arrays[name] = value;
  41279. return this;
  41280. };
  41281. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  41282. if (!mesh) {
  41283. return true;
  41284. }
  41285. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  41286. return false;
  41287. }
  41288. return false;
  41289. };
  41290. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  41291. var scene = this.getScene();
  41292. var engine = scene.getEngine();
  41293. if (!this.checkReadyOnEveryCall) {
  41294. if (this._renderId === scene.getRenderId()) {
  41295. if (this._checkCache(scene, mesh, useInstances)) {
  41296. return true;
  41297. }
  41298. }
  41299. }
  41300. // Instances
  41301. var defines = [];
  41302. var attribs = [];
  41303. var fallbacks = new BABYLON.EffectFallbacks();
  41304. if (useInstances) {
  41305. defines.push("#define INSTANCES");
  41306. }
  41307. for (var index = 0; index < this._options.defines.length; index++) {
  41308. defines.push(this._options.defines[index]);
  41309. }
  41310. for (var index = 0; index < this._options.attributes.length; index++) {
  41311. attribs.push(this._options.attributes[index]);
  41312. }
  41313. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41314. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41315. defines.push("#define VERTEXCOLOR");
  41316. }
  41317. // Bones
  41318. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  41319. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41320. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41321. if (mesh.numBoneInfluencers > 4) {
  41322. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41323. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41324. }
  41325. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41326. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41327. fallbacks.addCPUSkinningFallback(0, mesh);
  41328. if (this._options.uniforms.indexOf("mBones") === -1) {
  41329. this._options.uniforms.push("mBones");
  41330. }
  41331. }
  41332. else {
  41333. defines.push("#define NUM_BONE_INFLUENCERS 0");
  41334. }
  41335. // Textures
  41336. for (var name in this._textures) {
  41337. if (!this._textures[name].isReady()) {
  41338. return false;
  41339. }
  41340. }
  41341. // Alpha test
  41342. if (engine.getAlphaTesting()) {
  41343. defines.push("#define ALPHATEST");
  41344. }
  41345. var previousEffect = this._effect;
  41346. var join = defines.join("\n");
  41347. this._effect = engine.createEffect(this._shaderPath, {
  41348. attributes: attribs,
  41349. uniformsNames: this._options.uniforms,
  41350. uniformBuffersNames: this._options.uniformBuffers,
  41351. samplers: this._options.samplers,
  41352. defines: join,
  41353. fallbacks: fallbacks,
  41354. onCompiled: this.onCompiled,
  41355. onError: this.onError
  41356. }, engine);
  41357. if (!this._effect.isReady()) {
  41358. return false;
  41359. }
  41360. if (previousEffect !== this._effect) {
  41361. scene.resetCachedMaterial();
  41362. }
  41363. this._renderId = scene.getRenderId();
  41364. return true;
  41365. };
  41366. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41367. var scene = this.getScene();
  41368. if (this._options.uniforms.indexOf("world") !== -1) {
  41369. this._effect.setMatrix("world", world);
  41370. }
  41371. if (this._options.uniforms.indexOf("worldView") !== -1) {
  41372. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  41373. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  41374. }
  41375. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  41376. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  41377. }
  41378. };
  41379. ShaderMaterial.prototype.bind = function (world, mesh) {
  41380. // Std values
  41381. this.bindOnlyWorldMatrix(world);
  41382. if (this.getScene().getCachedMaterial() !== this) {
  41383. if (this._options.uniforms.indexOf("view") !== -1) {
  41384. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  41385. }
  41386. if (this._options.uniforms.indexOf("projection") !== -1) {
  41387. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  41388. }
  41389. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  41390. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  41391. }
  41392. // Bones
  41393. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  41394. var name;
  41395. // Texture
  41396. for (name in this._textures) {
  41397. this._effect.setTexture(name, this._textures[name]);
  41398. }
  41399. // Texture arrays
  41400. for (name in this._textureArrays) {
  41401. this._effect.setTextureArray(name, this._textureArrays[name]);
  41402. }
  41403. // Float
  41404. for (name in this._floats) {
  41405. this._effect.setFloat(name, this._floats[name]);
  41406. }
  41407. // Float s
  41408. for (name in this._floatsArrays) {
  41409. this._effect.setArray(name, this._floatsArrays[name]);
  41410. }
  41411. // Color3
  41412. for (name in this._colors3) {
  41413. this._effect.setColor3(name, this._colors3[name]);
  41414. }
  41415. // Color4
  41416. for (name in this._colors4) {
  41417. var color = this._colors4[name];
  41418. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  41419. }
  41420. // Vector2
  41421. for (name in this._vectors2) {
  41422. this._effect.setVector2(name, this._vectors2[name]);
  41423. }
  41424. // Vector3
  41425. for (name in this._vectors3) {
  41426. this._effect.setVector3(name, this._vectors3[name]);
  41427. }
  41428. // Vector4
  41429. for (name in this._vectors4) {
  41430. this._effect.setVector4(name, this._vectors4[name]);
  41431. }
  41432. // Matrix
  41433. for (name in this._matrices) {
  41434. this._effect.setMatrix(name, this._matrices[name]);
  41435. }
  41436. // Matrix 3x3
  41437. for (name in this._matrices3x3) {
  41438. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  41439. }
  41440. // Matrix 2x2
  41441. for (name in this._matrices2x2) {
  41442. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  41443. }
  41444. // Vector3Array
  41445. for (name in this._vectors3Arrays) {
  41446. this._effect.setArray3(name, this._vectors3Arrays[name]);
  41447. }
  41448. }
  41449. this._afterBind(mesh);
  41450. };
  41451. ShaderMaterial.prototype.getActiveTextures = function () {
  41452. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41453. for (var name in this._textures) {
  41454. activeTextures.push(this._textures[name]);
  41455. }
  41456. for (var name in this._textureArrays) {
  41457. var array = this._textureArrays[name];
  41458. for (var index = 0; index < array.length; index++) {
  41459. activeTextures.push(array[index]);
  41460. }
  41461. }
  41462. return activeTextures;
  41463. };
  41464. ShaderMaterial.prototype.hasTexture = function (texture) {
  41465. if (_super.prototype.hasTexture.call(this, texture)) {
  41466. return true;
  41467. }
  41468. for (var name in this._textures) {
  41469. if (this._textures[name] === texture) {
  41470. return true;
  41471. }
  41472. }
  41473. for (var name in this._textureArrays) {
  41474. var array = this._textureArrays[name];
  41475. for (var index = 0; index < array.length; index++) {
  41476. if (array[index] === texture) {
  41477. return true;
  41478. }
  41479. }
  41480. }
  41481. return false;
  41482. };
  41483. ShaderMaterial.prototype.clone = function (name) {
  41484. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  41485. return newShaderMaterial;
  41486. };
  41487. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41488. if (forceDisposeTextures) {
  41489. var name;
  41490. for (name in this._textures) {
  41491. this._textures[name].dispose();
  41492. }
  41493. for (name in this._textureArrays) {
  41494. var array = this._textureArrays[name];
  41495. for (var index = 0; index < array.length; index++) {
  41496. array[index].dispose();
  41497. }
  41498. }
  41499. }
  41500. this._textures = {};
  41501. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41502. };
  41503. ShaderMaterial.prototype.serialize = function () {
  41504. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41505. serializationObject.customType = "BABYLON.ShaderMaterial";
  41506. serializationObject.options = this._options;
  41507. serializationObject.shaderPath = this._shaderPath;
  41508. var name;
  41509. // Texture
  41510. serializationObject.textures = {};
  41511. for (name in this._textures) {
  41512. serializationObject.textures[name] = this._textures[name].serialize();
  41513. }
  41514. // Texture arrays
  41515. serializationObject.textureArrays = {};
  41516. for (name in this._textureArrays) {
  41517. serializationObject.textureArrays[name] = [];
  41518. var array = this._textureArrays[name];
  41519. for (var index = 0; index < array.length; index++) {
  41520. serializationObject.textureArrays[name].push(array[index].serialize());
  41521. }
  41522. }
  41523. // Float
  41524. serializationObject.floats = {};
  41525. for (name in this._floats) {
  41526. serializationObject.floats[name] = this._floats[name];
  41527. }
  41528. // Float s
  41529. serializationObject.floatArrays = {};
  41530. for (name in this._floatsArrays) {
  41531. serializationObject.floatArrays[name] = this._floatsArrays[name];
  41532. }
  41533. // Color3
  41534. serializationObject.colors3 = {};
  41535. for (name in this._colors3) {
  41536. serializationObject.colors3[name] = this._colors3[name].asArray();
  41537. }
  41538. // Color4
  41539. serializationObject.colors4 = {};
  41540. for (name in this._colors4) {
  41541. serializationObject.colors4[name] = this._colors4[name].asArray();
  41542. }
  41543. // Vector2
  41544. serializationObject.vectors2 = {};
  41545. for (name in this._vectors2) {
  41546. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  41547. }
  41548. // Vector3
  41549. serializationObject.vectors3 = {};
  41550. for (name in this._vectors3) {
  41551. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  41552. }
  41553. // Vector4
  41554. serializationObject.vectors4 = {};
  41555. for (name in this._vectors4) {
  41556. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  41557. }
  41558. // Matrix
  41559. serializationObject.matrices = {};
  41560. for (name in this._matrices) {
  41561. serializationObject.matrices[name] = this._matrices[name].asArray();
  41562. }
  41563. // Matrix 3x3
  41564. serializationObject.matrices3x3 = {};
  41565. for (name in this._matrices3x3) {
  41566. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  41567. }
  41568. // Matrix 2x2
  41569. serializationObject.matrices2x2 = {};
  41570. for (name in this._matrices2x2) {
  41571. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  41572. }
  41573. // Vector3Array
  41574. serializationObject.vectors3Arrays = {};
  41575. for (name in this._vectors3Arrays) {
  41576. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  41577. }
  41578. return serializationObject;
  41579. };
  41580. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  41581. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  41582. var name;
  41583. // Texture
  41584. for (name in source.textures) {
  41585. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  41586. }
  41587. // Texture arrays
  41588. for (name in source.textureArrays) {
  41589. var array = source.textureArrays[name];
  41590. var textureArray = new Array();
  41591. for (var index = 0; index < array.length; index++) {
  41592. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  41593. }
  41594. material.setTextureArray(name, textureArray);
  41595. }
  41596. // Float
  41597. for (name in source.floats) {
  41598. material.setFloat(name, source.floats[name]);
  41599. }
  41600. // Float s
  41601. for (name in source.floatsArrays) {
  41602. material.setFloats(name, source.floatsArrays[name]);
  41603. }
  41604. // Color3
  41605. for (name in source.colors3) {
  41606. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  41607. }
  41608. // Color4
  41609. for (name in source.colors4) {
  41610. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  41611. }
  41612. // Vector2
  41613. for (name in source.vectors2) {
  41614. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  41615. }
  41616. // Vector3
  41617. for (name in source.vectors3) {
  41618. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  41619. }
  41620. // Vector4
  41621. for (name in source.vectors4) {
  41622. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  41623. }
  41624. // Matrix
  41625. for (name in source.matrices) {
  41626. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  41627. }
  41628. // Matrix 3x3
  41629. for (name in source.matrices3x3) {
  41630. material.setMatrix3x3(name, source.matrices3x3[name]);
  41631. }
  41632. // Matrix 2x2
  41633. for (name in source.matrices2x2) {
  41634. material.setMatrix2x2(name, source.matrices2x2[name]);
  41635. }
  41636. // Vector3Array
  41637. for (name in source.vectors3Arrays) {
  41638. material.setArray3(name, source.vectors3Arrays[name]);
  41639. }
  41640. return material;
  41641. };
  41642. return ShaderMaterial;
  41643. }(BABYLON.Material));
  41644. BABYLON.ShaderMaterial = ShaderMaterial;
  41645. })(BABYLON || (BABYLON = {}));
  41646. //# sourceMappingURL=babylon.shaderMaterial.js.map
  41647. var BABYLON;
  41648. (function (BABYLON) {
  41649. var MeshBuilder = (function () {
  41650. function MeshBuilder() {
  41651. }
  41652. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  41653. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  41654. return BABYLON.Mesh.DOUBLESIDE;
  41655. }
  41656. if (orientation === undefined || orientation === null) {
  41657. return BABYLON.Mesh.FRONTSIDE;
  41658. }
  41659. return orientation;
  41660. };
  41661. /**
  41662. * Creates a box mesh.
  41663. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  41664. * The parameter `size` sets the size (float) of each box side (default 1).
  41665. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  41666. * 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).
  41667. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  41668. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41669. * 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).
  41670. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41672. */
  41673. MeshBuilder.CreateBox = function (name, options, scene) {
  41674. var box = new BABYLON.Mesh(name, scene);
  41675. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41676. box.sideOrientation = options.sideOrientation;
  41677. var vertexData = BABYLON.VertexData.CreateBox(options);
  41678. vertexData.applyToMesh(box, options.updatable);
  41679. return box;
  41680. };
  41681. /**
  41682. * Creates a sphere mesh.
  41683. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  41684. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  41685. * 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`).
  41686. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  41687. * 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
  41688. * 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).
  41689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41690. * 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).
  41691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41693. */
  41694. MeshBuilder.CreateSphere = function (name, options, scene) {
  41695. var sphere = new BABYLON.Mesh(name, scene);
  41696. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41697. sphere.sideOrientation = options.sideOrientation;
  41698. var vertexData = BABYLON.VertexData.CreateSphere(options);
  41699. vertexData.applyToMesh(sphere, options.updatable);
  41700. return sphere;
  41701. };
  41702. /**
  41703. * Creates a plane polygonal mesh. By default, this is a disc.
  41704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  41705. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  41706. * 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.
  41707. * 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
  41708. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41709. * 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).
  41710. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41712. */
  41713. MeshBuilder.CreateDisc = function (name, options, scene) {
  41714. var disc = new BABYLON.Mesh(name, scene);
  41715. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41716. disc.sideOrientation = options.sideOrientation;
  41717. var vertexData = BABYLON.VertexData.CreateDisc(options);
  41718. vertexData.applyToMesh(disc, options.updatable);
  41719. return disc;
  41720. };
  41721. /**
  41722. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  41723. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  41724. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  41725. * 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`).
  41726. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  41727. * 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.
  41728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41729. * 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).
  41730. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41732. */
  41733. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  41734. var sphere = new BABYLON.Mesh(name, scene);
  41735. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41736. sphere.sideOrientation = options.sideOrientation;
  41737. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  41738. vertexData.applyToMesh(sphere, options.updatable);
  41739. return sphere;
  41740. };
  41741. ;
  41742. /**
  41743. * Creates a ribbon mesh.
  41744. * 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.
  41745. *
  41746. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  41747. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  41748. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  41749. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  41750. * 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.
  41751. * 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.
  41752. * 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
  41753. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41754. * 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).
  41755. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41756. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41757. * 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.
  41758. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  41759. * 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
  41760. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  41761. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  41762. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41763. */
  41764. MeshBuilder.CreateRibbon = function (name, options, scene) {
  41765. var pathArray = options.pathArray;
  41766. var closeArray = options.closeArray;
  41767. var closePath = options.closePath;
  41768. var offset = options.offset;
  41769. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41770. var instance = options.instance;
  41771. var updatable = options.updatable;
  41772. if (instance) {
  41773. // positionFunction : ribbon case
  41774. // only pathArray and sideOrientation parameters are taken into account for positions update
  41775. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  41776. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  41777. var positionFunction = function (positions) {
  41778. var minlg = pathArray[0].length;
  41779. var i = 0;
  41780. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  41781. for (var si = 1; si <= ns; si++) {
  41782. for (var p = 0; p < pathArray.length; p++) {
  41783. var path = pathArray[p];
  41784. var l = path.length;
  41785. minlg = (minlg < l) ? minlg : l;
  41786. var j = 0;
  41787. while (j < minlg) {
  41788. positions[i] = path[j].x;
  41789. positions[i + 1] = path[j].y;
  41790. positions[i + 2] = path[j].z;
  41791. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  41792. BABYLON.Tmp.Vector3[0].x = path[j].x;
  41793. }
  41794. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  41795. BABYLON.Tmp.Vector3[1].x = path[j].x;
  41796. }
  41797. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  41798. BABYLON.Tmp.Vector3[0].y = path[j].y;
  41799. }
  41800. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  41801. BABYLON.Tmp.Vector3[1].y = path[j].y;
  41802. }
  41803. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  41804. BABYLON.Tmp.Vector3[0].z = path[j].z;
  41805. }
  41806. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  41807. BABYLON.Tmp.Vector3[1].z = path[j].z;
  41808. }
  41809. j++;
  41810. i += 3;
  41811. }
  41812. if (instance._closePath) {
  41813. positions[i] = path[0].x;
  41814. positions[i + 1] = path[0].y;
  41815. positions[i + 2] = path[0].z;
  41816. i += 3;
  41817. }
  41818. }
  41819. }
  41820. };
  41821. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41822. positionFunction(positions);
  41823. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  41824. instance._boundingInfo.update(instance._worldMatrix);
  41825. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  41826. if (options.colors) {
  41827. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41828. for (var c = 0; c < options.colors.length; c++) {
  41829. colors[c * 4] = options.colors[c].r;
  41830. colors[c * 4 + 1] = options.colors[c].g;
  41831. colors[c * 4 + 2] = options.colors[c].b;
  41832. colors[c * 4 + 3] = options.colors[c].a;
  41833. }
  41834. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  41835. }
  41836. if (options.uvs) {
  41837. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41838. for (var i = 0; i < options.uvs.length; i++) {
  41839. uvs[i * 2] = options.uvs[i].x;
  41840. uvs[i * 2 + 1] = options.uvs[i].y;
  41841. }
  41842. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  41843. }
  41844. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  41845. var indices = instance.getIndices();
  41846. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41847. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  41848. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  41849. if (instance._closePath) {
  41850. var indexFirst = 0;
  41851. var indexLast = 0;
  41852. for (var p = 0; p < pathArray.length; p++) {
  41853. indexFirst = instance._idx[p] * 3;
  41854. if (p + 1 < pathArray.length) {
  41855. indexLast = (instance._idx[p + 1] - 1) * 3;
  41856. }
  41857. else {
  41858. indexLast = normals.length - 3;
  41859. }
  41860. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  41861. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  41862. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  41863. normals[indexLast] = normals[indexFirst];
  41864. normals[indexLast + 1] = normals[indexFirst + 1];
  41865. normals[indexLast + 2] = normals[indexFirst + 2];
  41866. }
  41867. }
  41868. if (!(instance.areNormalsFrozen)) {
  41869. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  41870. }
  41871. }
  41872. return instance;
  41873. }
  41874. else {
  41875. var ribbon = new BABYLON.Mesh(name, scene);
  41876. ribbon.sideOrientation = sideOrientation;
  41877. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  41878. if (closePath) {
  41879. ribbon._idx = vertexData._idx;
  41880. }
  41881. ribbon._closePath = closePath;
  41882. ribbon._closeArray = closeArray;
  41883. vertexData.applyToMesh(ribbon, updatable);
  41884. return ribbon;
  41885. }
  41886. };
  41887. /**
  41888. * Creates a cylinder or a cone mesh.
  41889. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  41890. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  41891. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  41892. * 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.
  41893. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  41894. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  41895. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  41896. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  41897. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  41898. * 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).
  41899. * 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
  41900. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  41901. * 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
  41902. * 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.
  41903. * If `enclose` is false, a ring surface is one element.
  41904. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  41905. * 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
  41906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41907. * 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).
  41908. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41910. */
  41911. MeshBuilder.CreateCylinder = function (name, options, scene) {
  41912. var cylinder = new BABYLON.Mesh(name, scene);
  41913. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41914. cylinder.sideOrientation = options.sideOrientation;
  41915. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  41916. vertexData.applyToMesh(cylinder, options.updatable);
  41917. return cylinder;
  41918. };
  41919. /**
  41920. * Creates a torus mesh.
  41921. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  41922. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  41923. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  41924. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  41925. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41926. * 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).
  41927. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41928. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41929. */
  41930. MeshBuilder.CreateTorus = function (name, options, scene) {
  41931. var torus = new BABYLON.Mesh(name, scene);
  41932. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41933. torus.sideOrientation = options.sideOrientation;
  41934. var vertexData = BABYLON.VertexData.CreateTorus(options);
  41935. vertexData.applyToMesh(torus, options.updatable);
  41936. return torus;
  41937. };
  41938. /**
  41939. * Creates a torus knot mesh.
  41940. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  41941. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  41942. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  41943. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  41944. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  41945. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41946. * 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).
  41947. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41949. */
  41950. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  41951. var torusKnot = new BABYLON.Mesh(name, scene);
  41952. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41953. torusKnot.sideOrientation = options.sideOrientation;
  41954. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  41955. vertexData.applyToMesh(torusKnot, options.updatable);
  41956. return torusKnot;
  41957. };
  41958. /**
  41959. * Creates a line system mesh.
  41960. * A line system is a pool of many lines gathered in a single mesh.
  41961. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  41962. * 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.
  41963. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  41964. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  41965. * 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
  41966. * 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
  41967. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  41968. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41969. */
  41970. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  41971. var instance = options.instance;
  41972. var lines = options.lines;
  41973. if (instance) {
  41974. var positionFunction = function (positions) {
  41975. var i = 0;
  41976. for (var l = 0; l < lines.length; l++) {
  41977. var points = lines[l];
  41978. for (var p = 0; p < points.length; p++) {
  41979. positions[i] = points[p].x;
  41980. positions[i + 1] = points[p].y;
  41981. positions[i + 2] = points[p].z;
  41982. i += 3;
  41983. }
  41984. }
  41985. };
  41986. instance.updateMeshPositions(positionFunction, false);
  41987. return instance;
  41988. }
  41989. // line system creation
  41990. var lineSystem = new BABYLON.LinesMesh(name, scene);
  41991. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  41992. vertexData.applyToMesh(lineSystem, options.updatable);
  41993. return lineSystem;
  41994. };
  41995. /**
  41996. * Creates a line mesh.
  41997. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  41998. * 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.
  41999. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  42000. * The parameter `points` is an array successive Vector3.
  42001. * 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
  42002. * When updating an instance, remember that only point positions can change, not the number of points.
  42003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42004. */
  42005. MeshBuilder.CreateLines = function (name, options, scene) {
  42006. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  42007. return lines;
  42008. };
  42009. /**
  42010. * Creates a dashed line mesh.
  42011. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  42012. * 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.
  42013. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  42014. * The parameter `points` is an array successive Vector3.
  42015. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  42016. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  42017. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  42018. * 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
  42019. * When updating an instance, remember that only point positions can change, not the number of points.
  42020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42021. */
  42022. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  42023. var points = options.points;
  42024. var instance = options.instance;
  42025. var gapSize = options.gapSize;
  42026. var dashNb = options.dashNb;
  42027. var dashSize = options.dashSize;
  42028. if (instance) {
  42029. var positionFunction = function (positions) {
  42030. var curvect = BABYLON.Vector3.Zero();
  42031. var nbSeg = positions.length / 6;
  42032. var lg = 0;
  42033. var nb = 0;
  42034. var shft = 0;
  42035. var dashshft = 0;
  42036. var curshft = 0;
  42037. var p = 0;
  42038. var i = 0;
  42039. var j = 0;
  42040. for (i = 0; i < points.length - 1; i++) {
  42041. points[i + 1].subtractToRef(points[i], curvect);
  42042. lg += curvect.length();
  42043. }
  42044. shft = lg / nbSeg;
  42045. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  42046. for (i = 0; i < points.length - 1; i++) {
  42047. points[i + 1].subtractToRef(points[i], curvect);
  42048. nb = Math.floor(curvect.length() / shft);
  42049. curvect.normalize();
  42050. j = 0;
  42051. while (j < nb && p < positions.length) {
  42052. curshft = shft * j;
  42053. positions[p] = points[i].x + curshft * curvect.x;
  42054. positions[p + 1] = points[i].y + curshft * curvect.y;
  42055. positions[p + 2] = points[i].z + curshft * curvect.z;
  42056. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  42057. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  42058. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  42059. p += 6;
  42060. j++;
  42061. }
  42062. }
  42063. while (p < positions.length) {
  42064. positions[p] = points[i].x;
  42065. positions[p + 1] = points[i].y;
  42066. positions[p + 2] = points[i].z;
  42067. p += 3;
  42068. }
  42069. };
  42070. instance.updateMeshPositions(positionFunction, false);
  42071. return instance;
  42072. }
  42073. // dashed lines creation
  42074. var dashedLines = new BABYLON.LinesMesh(name, scene);
  42075. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  42076. vertexData.applyToMesh(dashedLines, options.updatable);
  42077. dashedLines.dashSize = dashSize;
  42078. dashedLines.gapSize = gapSize;
  42079. return dashedLines;
  42080. };
  42081. /**
  42082. * Creates an extruded shape mesh.
  42083. * 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.
  42084. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  42085. *
  42086. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  42087. * 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
  42088. * extruded along the Z axis.
  42089. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  42090. * 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.
  42091. * The parameter `scale` (float, default 1) is the value to scale the shape.
  42092. * 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
  42093. * 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
  42094. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  42095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42096. * 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).
  42097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42098. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42100. */
  42101. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  42102. var path = options.path;
  42103. var shape = options.shape;
  42104. var scale = options.scale || 1;
  42105. var rotation = options.rotation || 0;
  42106. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  42107. var updatable = options.updatable;
  42108. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42109. var instance = options.instance;
  42110. var invertUV = options.invertUV || false;
  42111. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  42112. };
  42113. /**
  42114. * Creates an custom extruded shape mesh.
  42115. * 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.
  42116. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  42117. *
  42118. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  42119. * 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
  42120. * extruded along the Z axis.
  42121. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  42122. * 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
  42123. * and the distance of this point from the begining of the path :
  42124. * ```javascript
  42125. * var rotationFunction = function(i, distance) {
  42126. * // do things
  42127. * return rotationValue; }
  42128. * ```
  42129. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  42130. * 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
  42131. * and the distance of this point from the begining of the path :
  42132. * ```javascript
  42133. * var scaleFunction = function(i, distance) {
  42134. * // do things
  42135. * return scaleValue;}
  42136. * ```
  42137. * It must returns a float value that will be the scale value applied to the shape on each path point.
  42138. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  42139. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  42140. * 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
  42141. * 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
  42142. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  42143. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42144. * 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).
  42145. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42146. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42147. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42148. */
  42149. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  42150. var path = options.path;
  42151. var shape = options.shape;
  42152. var scaleFunction = options.scaleFunction || (function () { return 1; });
  42153. var rotationFunction = options.rotationFunction || (function () { return 0; });
  42154. var ribbonCloseArray = options.ribbonCloseArray || false;
  42155. var ribbonClosePath = options.ribbonClosePath || false;
  42156. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  42157. var updatable = options.updatable;
  42158. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42159. var instance = options.instance;
  42160. var invertUV = options.invertUV || false;
  42161. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  42162. };
  42163. /**
  42164. * Creates lathe mesh.
  42165. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  42166. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  42167. *
  42168. * 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
  42169. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  42170. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  42171. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  42172. * 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.
  42173. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  42174. * 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
  42175. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42176. * 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).
  42177. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42178. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42179. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42180. */
  42181. MeshBuilder.CreateLathe = function (name, options, scene) {
  42182. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  42183. var closed = (options.closed === undefined) ? true : options.closed;
  42184. var shape = options.shape;
  42185. var radius = options.radius || 1;
  42186. var tessellation = options.tessellation || 64;
  42187. var updatable = options.updatable;
  42188. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42189. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  42190. var pi2 = Math.PI * 2;
  42191. var paths = new Array();
  42192. var invertUV = options.invertUV || false;
  42193. var i = 0;
  42194. var p = 0;
  42195. var step = pi2 / tessellation * arc;
  42196. var rotated;
  42197. var path = new Array();
  42198. ;
  42199. for (i = 0; i <= tessellation; i++) {
  42200. var path = [];
  42201. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  42202. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  42203. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  42204. }
  42205. for (p = 0; p < shape.length; p++) {
  42206. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  42207. path.push(rotated);
  42208. }
  42209. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  42210. 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));
  42211. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  42212. }
  42213. paths.push(path);
  42214. }
  42215. // lathe ribbon
  42216. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  42217. return lathe;
  42218. };
  42219. /**
  42220. * Creates a plane mesh.
  42221. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  42222. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  42223. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  42224. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  42225. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42226. * 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).
  42227. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42228. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42229. */
  42230. MeshBuilder.CreatePlane = function (name, options, scene) {
  42231. var plane = new BABYLON.Mesh(name, scene);
  42232. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42233. plane.sideOrientation = options.sideOrientation;
  42234. var vertexData = BABYLON.VertexData.CreatePlane(options);
  42235. vertexData.applyToMesh(plane, options.updatable);
  42236. if (options.sourcePlane) {
  42237. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  42238. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  42239. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  42240. plane.rotate(vectorProduct, product);
  42241. }
  42242. return plane;
  42243. };
  42244. /**
  42245. * Creates a ground mesh.
  42246. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  42247. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  42248. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  42249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42250. */
  42251. MeshBuilder.CreateGround = function (name, options, scene) {
  42252. var ground = new BABYLON.GroundMesh(name, scene);
  42253. ground._setReady(false);
  42254. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  42255. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  42256. ground._width = options.width || 1;
  42257. ground._height = options.height || 1;
  42258. ground._maxX = ground._width / 2;
  42259. ground._maxZ = ground._height / 2;
  42260. ground._minX = -ground._maxX;
  42261. ground._minZ = -ground._maxZ;
  42262. var vertexData = BABYLON.VertexData.CreateGround(options);
  42263. vertexData.applyToMesh(ground, options.updatable);
  42264. ground._setReady(true);
  42265. return ground;
  42266. };
  42267. /**
  42268. * Creates a tiled ground mesh.
  42269. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  42270. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  42271. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  42272. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  42273. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  42274. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  42275. * numbers of subdivisions on the ground width and height of each tile.
  42276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42277. */
  42278. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  42279. var tiledGround = new BABYLON.Mesh(name, scene);
  42280. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  42281. vertexData.applyToMesh(tiledGround, options.updatable);
  42282. return tiledGround;
  42283. };
  42284. /**
  42285. * Creates a ground mesh from a height map.
  42286. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  42287. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  42288. * The parameter `url` sets the URL of the height map image resource.
  42289. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  42290. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  42291. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  42292. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  42293. * 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.
  42294. * 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).
  42295. * This function is passed the newly built mesh :
  42296. * ```javascript
  42297. * function(mesh) { // do things
  42298. * return; }
  42299. * ```
  42300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42301. */
  42302. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  42303. var width = options.width || 10.0;
  42304. var height = options.height || 10.0;
  42305. var subdivisions = options.subdivisions || 1 | 0;
  42306. var minHeight = options.minHeight || 0.0;
  42307. var maxHeight = options.maxHeight || 10.0;
  42308. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  42309. var updatable = options.updatable;
  42310. var onReady = options.onReady;
  42311. var ground = new BABYLON.GroundMesh(name, scene);
  42312. ground._subdivisionsX = subdivisions;
  42313. ground._subdivisionsY = subdivisions;
  42314. ground._width = width;
  42315. ground._height = height;
  42316. ground._maxX = ground._width / 2.0;
  42317. ground._maxZ = ground._height / 2.0;
  42318. ground._minX = -ground._maxX;
  42319. ground._minZ = -ground._maxZ;
  42320. ground._setReady(false);
  42321. var onload = function (img) {
  42322. // Getting height map data
  42323. var canvas = document.createElement("canvas");
  42324. var context = canvas.getContext("2d");
  42325. var bufferWidth = img.width;
  42326. var bufferHeight = img.height;
  42327. canvas.width = bufferWidth;
  42328. canvas.height = bufferHeight;
  42329. context.drawImage(img, 0, 0);
  42330. // Create VertexData from map data
  42331. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  42332. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  42333. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  42334. width: width, height: height,
  42335. subdivisions: subdivisions,
  42336. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  42337. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  42338. });
  42339. vertexData.applyToMesh(ground, updatable);
  42340. ground._setReady(true);
  42341. //execute ready callback, if set
  42342. if (onReady) {
  42343. onReady(ground);
  42344. }
  42345. };
  42346. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  42347. return ground;
  42348. };
  42349. /**
  42350. * Creates a polygon mesh.
  42351. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  42352. * 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.
  42353. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42354. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42355. * 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).
  42356. * Remember you can only change the shape positions, not their number when updating a polygon.
  42357. */
  42358. MeshBuilder.CreatePolygon = function (name, options, scene) {
  42359. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42360. var shape = options.shape;
  42361. var holes = options.holes || [];
  42362. var depth = options.depth || 0;
  42363. var contours = [];
  42364. var hole = [];
  42365. for (var i = 0; i < shape.length; i++) {
  42366. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  42367. }
  42368. var epsilon = 0.00000001;
  42369. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  42370. contours.pop();
  42371. }
  42372. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  42373. for (var hNb = 0; hNb < holes.length; hNb++) {
  42374. hole = [];
  42375. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  42376. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  42377. }
  42378. polygonTriangulation.addHole(hole);
  42379. }
  42380. var polygon = polygonTriangulation.build(options.updatable, depth);
  42381. polygon.sideOrientation = options.sideOrientation;
  42382. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  42383. vertexData.applyToMesh(polygon, options.updatable);
  42384. return polygon;
  42385. };
  42386. ;
  42387. /**
  42388. * Creates an extruded polygon mesh, with depth in the Y direction.
  42389. * 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).
  42390. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  42391. */
  42392. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  42393. return MeshBuilder.CreatePolygon(name, options, scene);
  42394. };
  42395. ;
  42396. /**
  42397. * Creates a tube mesh.
  42398. * 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.
  42399. *
  42400. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  42401. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  42402. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  42403. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  42404. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  42405. * 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.
  42406. * It must return a radius value (positive float) :
  42407. * ```javascript
  42408. * var radiusFunction = function(i, distance) {
  42409. * // do things
  42410. * return radius; }
  42411. * ```
  42412. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  42413. * 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
  42414. * 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
  42415. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42416. * 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).
  42417. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42418. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42420. */
  42421. MeshBuilder.CreateTube = function (name, options, scene) {
  42422. var path = options.path;
  42423. var radius = options.radius || 1.0;
  42424. var tessellation = options.tessellation || 64 | 0;
  42425. var radiusFunction = options.radiusFunction;
  42426. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  42427. var invertUV = options.invertUV || false;
  42428. var updatable = options.updatable;
  42429. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42430. var instance = options.instance;
  42431. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  42432. // tube geometry
  42433. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  42434. var tangents = path3D.getTangents();
  42435. var normals = path3D.getNormals();
  42436. var distances = path3D.getDistances();
  42437. var pi2 = Math.PI * 2;
  42438. var step = pi2 / tessellation * arc;
  42439. var returnRadius = function () { return radius; };
  42440. var radiusFunctionFinal = radiusFunction || returnRadius;
  42441. var circlePath;
  42442. var rad;
  42443. var normal;
  42444. var rotated;
  42445. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  42446. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  42447. for (var i = 0; i < path.length; i++) {
  42448. rad = radiusFunctionFinal(i, distances[i]); // current radius
  42449. circlePath = Array(); // current circle array
  42450. normal = normals[i]; // current normal
  42451. for (var t = 0; t < tessellation; t++) {
  42452. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  42453. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  42454. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  42455. rotated.scaleInPlace(rad).addInPlace(path[i]);
  42456. circlePath[t] = rotated;
  42457. }
  42458. circlePaths[index] = circlePath;
  42459. index++;
  42460. }
  42461. // cap
  42462. var capPath = function (nbPoints, pathIndex) {
  42463. var pointCap = Array();
  42464. for (var i = 0; i < nbPoints; i++) {
  42465. pointCap.push(path[pathIndex]);
  42466. }
  42467. return pointCap;
  42468. };
  42469. switch (cap) {
  42470. case BABYLON.Mesh.NO_CAP:
  42471. break;
  42472. case BABYLON.Mesh.CAP_START:
  42473. circlePaths[0] = capPath(tessellation, 0);
  42474. circlePaths[1] = circlePaths[2].slice(0);
  42475. break;
  42476. case BABYLON.Mesh.CAP_END:
  42477. circlePaths[index] = circlePaths[index - 1].slice(0);
  42478. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  42479. break;
  42480. case BABYLON.Mesh.CAP_ALL:
  42481. circlePaths[0] = capPath(tessellation, 0);
  42482. circlePaths[1] = circlePaths[2].slice(0);
  42483. circlePaths[index] = circlePaths[index - 1].slice(0);
  42484. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  42485. break;
  42486. default:
  42487. break;
  42488. }
  42489. return circlePaths;
  42490. };
  42491. var path3D;
  42492. var pathArray;
  42493. if (instance) {
  42494. var arc = options.arc || instance.arc;
  42495. path3D = (instance.path3D).update(path);
  42496. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  42497. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  42498. instance.path3D = path3D;
  42499. instance.pathArray = pathArray;
  42500. instance.arc = arc;
  42501. return instance;
  42502. }
  42503. // tube creation
  42504. path3D = new BABYLON.Path3D(path);
  42505. var newPathArray = new Array();
  42506. cap = (cap < 0 || cap > 3) ? 0 : cap;
  42507. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  42508. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  42509. tube.pathArray = pathArray;
  42510. tube.path3D = path3D;
  42511. tube.tessellation = tessellation;
  42512. tube.cap = cap;
  42513. tube.arc = options.arc;
  42514. return tube;
  42515. };
  42516. /**
  42517. * Creates a polyhedron mesh.
  42518. *
  42519. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  42520. * 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
  42521. * to choose the wanted type.
  42522. * The parameter `size` (positive float, default 1) sets the polygon size.
  42523. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  42524. * 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`.
  42525. * 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
  42526. * 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)`).
  42527. * 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
  42528. * 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.
  42529. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42530. * 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).
  42531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42533. */
  42534. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  42535. var polyhedron = new BABYLON.Mesh(name, scene);
  42536. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42537. polyhedron.sideOrientation = options.sideOrientation;
  42538. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  42539. vertexData.applyToMesh(polyhedron, options.updatable);
  42540. return polyhedron;
  42541. };
  42542. /**
  42543. * Creates a decal mesh.
  42544. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  42545. * 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.
  42546. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  42547. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  42548. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  42549. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  42550. */
  42551. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  42552. var indices = sourceMesh.getIndices();
  42553. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42554. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42555. var position = options.position || BABYLON.Vector3.Zero();
  42556. var normal = options.normal || BABYLON.Vector3.Up();
  42557. var size = options.size || BABYLON.Vector3.One();
  42558. var angle = options.angle || 0;
  42559. // Getting correct rotation
  42560. if (!normal) {
  42561. var target = new BABYLON.Vector3(0, 0, 1);
  42562. var camera = sourceMesh.getScene().activeCamera;
  42563. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  42564. normal = camera.globalPosition.subtract(cameraWorldTarget);
  42565. }
  42566. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  42567. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  42568. var pitch = Math.atan2(normal.y, len);
  42569. // Matrix
  42570. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  42571. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  42572. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  42573. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  42574. var vertexData = new BABYLON.VertexData();
  42575. vertexData.indices = [];
  42576. vertexData.positions = [];
  42577. vertexData.normals = [];
  42578. vertexData.uvs = [];
  42579. var currentVertexDataIndex = 0;
  42580. var extractDecalVector3 = function (indexId) {
  42581. var vertexId = indices[indexId];
  42582. var result = new BABYLON.PositionNormalVertex();
  42583. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  42584. // Send vector to decal local world
  42585. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  42586. // Get normal
  42587. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  42588. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  42589. return result;
  42590. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  42591. var clip = function (vertices, axis) {
  42592. if (vertices.length === 0) {
  42593. return vertices;
  42594. }
  42595. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  42596. var clipVertices = function (v0, v1) {
  42597. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  42598. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  42599. };
  42600. var result = new Array();
  42601. for (var index = 0; index < vertices.length; index += 3) {
  42602. var v1Out;
  42603. var v2Out;
  42604. var v3Out;
  42605. var total = 0;
  42606. var nV1, nV2, nV3, nV4;
  42607. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  42608. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  42609. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  42610. v1Out = d1 > 0;
  42611. v2Out = d2 > 0;
  42612. v3Out = d3 > 0;
  42613. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  42614. switch (total) {
  42615. case 0:
  42616. result.push(vertices[index]);
  42617. result.push(vertices[index + 1]);
  42618. result.push(vertices[index + 2]);
  42619. break;
  42620. case 1:
  42621. if (v1Out) {
  42622. nV1 = vertices[index + 1];
  42623. nV2 = vertices[index + 2];
  42624. nV3 = clipVertices(vertices[index], nV1);
  42625. nV4 = clipVertices(vertices[index], nV2);
  42626. }
  42627. if (v2Out) {
  42628. nV1 = vertices[index];
  42629. nV2 = vertices[index + 2];
  42630. nV3 = clipVertices(vertices[index + 1], nV1);
  42631. nV4 = clipVertices(vertices[index + 1], nV2);
  42632. result.push(nV3);
  42633. result.push(nV2.clone());
  42634. result.push(nV1.clone());
  42635. result.push(nV2.clone());
  42636. result.push(nV3.clone());
  42637. result.push(nV4);
  42638. break;
  42639. }
  42640. if (v3Out) {
  42641. nV1 = vertices[index];
  42642. nV2 = vertices[index + 1];
  42643. nV3 = clipVertices(vertices[index + 2], nV1);
  42644. nV4 = clipVertices(vertices[index + 2], nV2);
  42645. }
  42646. result.push(nV1.clone());
  42647. result.push(nV2.clone());
  42648. result.push(nV3);
  42649. result.push(nV4);
  42650. result.push(nV3.clone());
  42651. result.push(nV2.clone());
  42652. break;
  42653. case 2:
  42654. if (!v1Out) {
  42655. nV1 = vertices[index].clone();
  42656. nV2 = clipVertices(nV1, vertices[index + 1]);
  42657. nV3 = clipVertices(nV1, vertices[index + 2]);
  42658. result.push(nV1);
  42659. result.push(nV2);
  42660. result.push(nV3);
  42661. }
  42662. if (!v2Out) {
  42663. nV1 = vertices[index + 1].clone();
  42664. nV2 = clipVertices(nV1, vertices[index + 2]);
  42665. nV3 = clipVertices(nV1, vertices[index]);
  42666. result.push(nV1);
  42667. result.push(nV2);
  42668. result.push(nV3);
  42669. }
  42670. if (!v3Out) {
  42671. nV1 = vertices[index + 2].clone();
  42672. nV2 = clipVertices(nV1, vertices[index]);
  42673. nV3 = clipVertices(nV1, vertices[index + 1]);
  42674. result.push(nV1);
  42675. result.push(nV2);
  42676. result.push(nV3);
  42677. }
  42678. break;
  42679. case 3:
  42680. break;
  42681. }
  42682. }
  42683. return result;
  42684. };
  42685. for (var index = 0; index < indices.length; index += 3) {
  42686. var faceVertices = new Array();
  42687. faceVertices.push(extractDecalVector3(index));
  42688. faceVertices.push(extractDecalVector3(index + 1));
  42689. faceVertices.push(extractDecalVector3(index + 2));
  42690. // Clip
  42691. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  42692. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  42693. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  42694. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  42695. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  42696. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  42697. if (faceVertices.length === 0) {
  42698. continue;
  42699. }
  42700. // Add UVs and get back to world
  42701. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  42702. var vertex = faceVertices[vIndex];
  42703. //TODO check for Int32Array | Uint32Array | Uint16Array
  42704. vertexData.indices.push(currentVertexDataIndex);
  42705. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  42706. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  42707. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  42708. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  42709. currentVertexDataIndex++;
  42710. }
  42711. }
  42712. // Return mesh
  42713. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  42714. vertexData.applyToMesh(decal);
  42715. decal.position = position.clone();
  42716. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  42717. return decal;
  42718. };
  42719. // Privates
  42720. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  42721. // extrusion geometry
  42722. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  42723. var tangents = path3D.getTangents();
  42724. var normals = path3D.getNormals();
  42725. var binormals = path3D.getBinormals();
  42726. var distances = path3D.getDistances();
  42727. var angle = 0;
  42728. var returnScale = function () { return scale; };
  42729. var returnRotation = function () { return rotation; };
  42730. var rotate = custom ? rotateFunction : returnRotation;
  42731. var scl = custom ? scaleFunction : returnScale;
  42732. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  42733. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  42734. for (var i = 0; i < curve.length; i++) {
  42735. var shapePath = new Array();
  42736. var angleStep = rotate(i, distances[i]);
  42737. var scaleRatio = scl(i, distances[i]);
  42738. for (var p = 0; p < shape.length; p++) {
  42739. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  42740. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  42741. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  42742. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  42743. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  42744. shapePath[p] = rotated;
  42745. }
  42746. shapePaths[index] = shapePath;
  42747. angle += angleStep;
  42748. index++;
  42749. }
  42750. // cap
  42751. var capPath = function (shapePath) {
  42752. var pointCap = Array();
  42753. var barycenter = BABYLON.Vector3.Zero();
  42754. var i;
  42755. for (i = 0; i < shapePath.length; i++) {
  42756. barycenter.addInPlace(shapePath[i]);
  42757. }
  42758. barycenter.scaleInPlace(1.0 / shapePath.length);
  42759. for (i = 0; i < shapePath.length; i++) {
  42760. pointCap.push(barycenter);
  42761. }
  42762. return pointCap;
  42763. };
  42764. switch (cap) {
  42765. case BABYLON.Mesh.NO_CAP:
  42766. break;
  42767. case BABYLON.Mesh.CAP_START:
  42768. shapePaths[0] = capPath(shapePaths[2]);
  42769. shapePaths[1] = shapePaths[2];
  42770. break;
  42771. case BABYLON.Mesh.CAP_END:
  42772. shapePaths[index] = shapePaths[index - 1];
  42773. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  42774. break;
  42775. case BABYLON.Mesh.CAP_ALL:
  42776. shapePaths[0] = capPath(shapePaths[2]);
  42777. shapePaths[1] = shapePaths[2];
  42778. shapePaths[index] = shapePaths[index - 1];
  42779. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  42780. break;
  42781. default:
  42782. break;
  42783. }
  42784. return shapePaths;
  42785. };
  42786. var path3D;
  42787. var pathArray;
  42788. if (instance) {
  42789. path3D = (instance.path3D).update(curve);
  42790. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  42791. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  42792. return instance;
  42793. }
  42794. // extruded shape creation
  42795. path3D = new BABYLON.Path3D(curve);
  42796. var newShapePaths = new Array();
  42797. cap = (cap < 0 || cap > 3) ? 0 : cap;
  42798. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  42799. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  42800. extrudedGeneric.pathArray = pathArray;
  42801. extrudedGeneric.path3D = path3D;
  42802. extrudedGeneric.cap = cap;
  42803. return extrudedGeneric;
  42804. };
  42805. return MeshBuilder;
  42806. }());
  42807. BABYLON.MeshBuilder = MeshBuilder;
  42808. })(BABYLON || (BABYLON = {}));
  42809. //# sourceMappingURL=babylon.meshBuilder.js.map
  42810. var BABYLON;
  42811. (function (BABYLON) {
  42812. var AudioEngine = (function () {
  42813. function AudioEngine() {
  42814. this._audioContext = null;
  42815. this._audioContextInitialized = false;
  42816. this.canUseWebAudio = false;
  42817. this.WarnedWebAudioUnsupported = false;
  42818. this.unlocked = false;
  42819. this.isMP3supported = false;
  42820. this.isOGGsupported = false;
  42821. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  42822. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  42823. this.canUseWebAudio = true;
  42824. }
  42825. var audioElem = document.createElement('audio');
  42826. try {
  42827. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  42828. this.isMP3supported = true;
  42829. }
  42830. }
  42831. catch (e) {
  42832. // protect error during capability check.
  42833. }
  42834. try {
  42835. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  42836. this.isOGGsupported = true;
  42837. }
  42838. }
  42839. catch (e) {
  42840. // protect error during capability check.
  42841. }
  42842. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  42843. this._unlockiOSaudio();
  42844. }
  42845. else {
  42846. this.unlocked = true;
  42847. }
  42848. }
  42849. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  42850. get: function () {
  42851. if (!this._audioContextInitialized) {
  42852. this._initializeAudioContext();
  42853. }
  42854. return this._audioContext;
  42855. },
  42856. enumerable: true,
  42857. configurable: true
  42858. });
  42859. AudioEngine.prototype._unlockiOSaudio = function () {
  42860. var _this = this;
  42861. var unlockaudio = function () {
  42862. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  42863. var source = _this.audioContext.createBufferSource();
  42864. source.buffer = buffer;
  42865. source.connect(_this.audioContext.destination);
  42866. source.start(0);
  42867. setTimeout(function () {
  42868. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  42869. _this.unlocked = true;
  42870. window.removeEventListener('touchend', unlockaudio, false);
  42871. if (_this.onAudioUnlocked) {
  42872. _this.onAudioUnlocked();
  42873. }
  42874. }
  42875. }, 0);
  42876. };
  42877. window.addEventListener('touchend', unlockaudio, false);
  42878. };
  42879. AudioEngine.prototype._initializeAudioContext = function () {
  42880. try {
  42881. if (this.canUseWebAudio) {
  42882. this._audioContext = new AudioContext();
  42883. // create a global volume gain node
  42884. this.masterGain = this._audioContext.createGain();
  42885. this.masterGain.gain.value = 1;
  42886. this.masterGain.connect(this._audioContext.destination);
  42887. this._audioContextInitialized = true;
  42888. }
  42889. }
  42890. catch (e) {
  42891. this.canUseWebAudio = false;
  42892. BABYLON.Tools.Error("Web Audio: " + e.message);
  42893. }
  42894. };
  42895. AudioEngine.prototype.dispose = function () {
  42896. if (this.canUseWebAudio && this._audioContextInitialized) {
  42897. if (this._connectedAnalyser) {
  42898. this._connectedAnalyser.stopDebugCanvas();
  42899. this._connectedAnalyser.dispose();
  42900. this.masterGain.disconnect();
  42901. this.masterGain.connect(this._audioContext.destination);
  42902. this._connectedAnalyser = null;
  42903. }
  42904. this.masterGain.gain.value = 1;
  42905. }
  42906. this.WarnedWebAudioUnsupported = false;
  42907. };
  42908. AudioEngine.prototype.getGlobalVolume = function () {
  42909. if (this.canUseWebAudio && this._audioContextInitialized) {
  42910. return this.masterGain.gain.value;
  42911. }
  42912. else {
  42913. return -1;
  42914. }
  42915. };
  42916. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  42917. if (this.canUseWebAudio && this._audioContextInitialized) {
  42918. this.masterGain.gain.value = newVolume;
  42919. }
  42920. };
  42921. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  42922. if (this._connectedAnalyser) {
  42923. this._connectedAnalyser.stopDebugCanvas();
  42924. }
  42925. if (this.canUseWebAudio && this._audioContextInitialized) {
  42926. this._connectedAnalyser = analyser;
  42927. this.masterGain.disconnect();
  42928. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  42929. }
  42930. };
  42931. return AudioEngine;
  42932. }());
  42933. BABYLON.AudioEngine = AudioEngine;
  42934. })(BABYLON || (BABYLON = {}));
  42935. //# sourceMappingURL=babylon.audioEngine.js.map
  42936. var BABYLON;
  42937. (function (BABYLON) {
  42938. var Sound = (function () {
  42939. /**
  42940. * Create a sound and attach it to a scene
  42941. * @param name Name of your sound
  42942. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  42943. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  42944. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  42945. */
  42946. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  42947. var _this = this;
  42948. this.autoplay = false;
  42949. this.loop = false;
  42950. this.useCustomAttenuation = false;
  42951. this.spatialSound = false;
  42952. this.refDistance = 1;
  42953. this.rolloffFactor = 1;
  42954. this.maxDistance = 100;
  42955. this.distanceModel = "linear";
  42956. this._panningModel = "equalpower";
  42957. this._playbackRate = 1;
  42958. this._streaming = false;
  42959. this._startTime = 0;
  42960. this._startOffset = 0;
  42961. this._position = BABYLON.Vector3.Zero();
  42962. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  42963. this._volume = 1;
  42964. this._isLoaded = false;
  42965. this._isReadyToPlay = false;
  42966. this.isPlaying = false;
  42967. this.isPaused = false;
  42968. this._isDirectional = false;
  42969. // Used if you'd like to create a directional sound.
  42970. // If not set, the sound will be omnidirectional
  42971. this._coneInnerAngle = 360;
  42972. this._coneOuterAngle = 360;
  42973. this._coneOuterGain = 0;
  42974. this._isOutputConnected = false;
  42975. this._urlType = "Unknown";
  42976. this.name = name;
  42977. this._scene = scene;
  42978. this._readyToPlayCallback = readyToPlayCallback;
  42979. // Default custom attenuation function is a linear attenuation
  42980. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  42981. if (currentDistance < maxDistance) {
  42982. return currentVolume * (1 - currentDistance / maxDistance);
  42983. }
  42984. else {
  42985. return 0;
  42986. }
  42987. };
  42988. if (options) {
  42989. this.autoplay = options.autoplay || false;
  42990. this.loop = options.loop || false;
  42991. // if volume === 0, we need another way to check this option
  42992. if (options.volume !== undefined) {
  42993. this._volume = options.volume;
  42994. }
  42995. this.spatialSound = options.spatialSound || false;
  42996. this.maxDistance = options.maxDistance || 100;
  42997. this.useCustomAttenuation = options.useCustomAttenuation || false;
  42998. this.rolloffFactor = options.rolloffFactor || 1;
  42999. this.refDistance = options.refDistance || 1;
  43000. this.distanceModel = options.distanceModel || "linear";
  43001. this._playbackRate = options.playbackRate || 1;
  43002. this._streaming = options.streaming || false;
  43003. }
  43004. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43005. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  43006. this._soundGain.gain.value = this._volume;
  43007. this._inputAudioNode = this._soundGain;
  43008. this._ouputAudioNode = this._soundGain;
  43009. if (this.spatialSound) {
  43010. this._createSpatialParameters();
  43011. }
  43012. this._scene.mainSoundTrack.AddSound(this);
  43013. var validParameter = true;
  43014. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  43015. if (urlOrArrayBuffer) {
  43016. if (typeof (urlOrArrayBuffer) === "string")
  43017. this._urlType = "String";
  43018. if (Array.isArray(urlOrArrayBuffer))
  43019. this._urlType = "Array";
  43020. if (urlOrArrayBuffer instanceof ArrayBuffer)
  43021. this._urlType = "ArrayBuffer";
  43022. var urls = [];
  43023. var codecSupportedFound = false;
  43024. switch (this._urlType) {
  43025. case "ArrayBuffer":
  43026. if (urlOrArrayBuffer.byteLength > 0) {
  43027. codecSupportedFound = true;
  43028. this._soundLoaded(urlOrArrayBuffer);
  43029. }
  43030. break;
  43031. case "String":
  43032. urls.push(urlOrArrayBuffer);
  43033. case "Array":
  43034. if (urls.length === 0)
  43035. urls = urlOrArrayBuffer;
  43036. // If we found a supported format, we load it immediately and stop the loop
  43037. for (var i = 0; i < urls.length; i++) {
  43038. var url = urls[i];
  43039. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  43040. codecSupportedFound = true;
  43041. }
  43042. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  43043. codecSupportedFound = true;
  43044. }
  43045. if (url.indexOf(".wav", url.length - 4) !== -1) {
  43046. codecSupportedFound = true;
  43047. }
  43048. if (codecSupportedFound) {
  43049. // Loading sound using XHR2
  43050. if (!this._streaming) {
  43051. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  43052. }
  43053. else {
  43054. this._htmlAudioElement = new Audio(url);
  43055. this._htmlAudioElement.controls = false;
  43056. this._htmlAudioElement.loop = this.loop;
  43057. this._htmlAudioElement.crossOrigin = "anonymous";
  43058. this._htmlAudioElement.preload = "auto";
  43059. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  43060. _this._isReadyToPlay = true;
  43061. if (_this.autoplay) {
  43062. _this.play();
  43063. }
  43064. if (_this._readyToPlayCallback) {
  43065. _this._readyToPlayCallback();
  43066. }
  43067. });
  43068. document.body.appendChild(this._htmlAudioElement);
  43069. }
  43070. break;
  43071. }
  43072. }
  43073. break;
  43074. default:
  43075. validParameter = false;
  43076. break;
  43077. }
  43078. if (!validParameter) {
  43079. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  43080. }
  43081. else {
  43082. if (!codecSupportedFound) {
  43083. this._isReadyToPlay = true;
  43084. // Simulating a ready to play event to avoid breaking code path
  43085. if (this._readyToPlayCallback) {
  43086. window.setTimeout(function () {
  43087. _this._readyToPlayCallback();
  43088. }, 1000);
  43089. }
  43090. }
  43091. }
  43092. }
  43093. }
  43094. else {
  43095. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  43096. this._scene.mainSoundTrack.AddSound(this);
  43097. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  43098. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  43099. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  43100. }
  43101. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  43102. if (this._readyToPlayCallback) {
  43103. window.setTimeout(function () {
  43104. _this._readyToPlayCallback();
  43105. }, 1000);
  43106. }
  43107. }
  43108. }
  43109. Sound.prototype.dispose = function () {
  43110. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  43111. if (this.isPlaying) {
  43112. this.stop();
  43113. }
  43114. this._isReadyToPlay = false;
  43115. if (this.soundTrackId === -1) {
  43116. this._scene.mainSoundTrack.RemoveSound(this);
  43117. }
  43118. else {
  43119. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  43120. }
  43121. if (this._soundGain) {
  43122. this._soundGain.disconnect();
  43123. this._soundGain = null;
  43124. }
  43125. if (this._soundPanner) {
  43126. this._soundPanner.disconnect();
  43127. this._soundPanner = null;
  43128. }
  43129. if (this._soundSource) {
  43130. this._soundSource.disconnect();
  43131. this._soundSource = null;
  43132. }
  43133. this._audioBuffer = null;
  43134. if (this._htmlAudioElement) {
  43135. this._htmlAudioElement.pause();
  43136. this._htmlAudioElement.src = "";
  43137. document.body.removeChild(this._htmlAudioElement);
  43138. }
  43139. if (this._connectedMesh) {
  43140. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43141. this._connectedMesh = null;
  43142. }
  43143. }
  43144. };
  43145. Sound.prototype.isReady = function () {
  43146. return this._isReadyToPlay;
  43147. };
  43148. Sound.prototype._soundLoaded = function (audioData) {
  43149. var _this = this;
  43150. this._isLoaded = true;
  43151. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  43152. _this._audioBuffer = buffer;
  43153. _this._isReadyToPlay = true;
  43154. if (_this.autoplay) {
  43155. _this.play();
  43156. }
  43157. if (_this._readyToPlayCallback) {
  43158. _this._readyToPlayCallback();
  43159. }
  43160. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  43161. };
  43162. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  43163. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43164. this._audioBuffer = audioBuffer;
  43165. this._isReadyToPlay = true;
  43166. }
  43167. };
  43168. Sound.prototype.updateOptions = function (options) {
  43169. if (options) {
  43170. this.loop = options.loop || this.loop;
  43171. this.maxDistance = options.maxDistance || this.maxDistance;
  43172. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  43173. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  43174. this.refDistance = options.refDistance || this.refDistance;
  43175. this.distanceModel = options.distanceModel || this.distanceModel;
  43176. this._playbackRate = options.playbackRate || this._playbackRate;
  43177. this._updateSpatialParameters();
  43178. if (this.isPlaying) {
  43179. if (this._streaming) {
  43180. this._htmlAudioElement.playbackRate = this._playbackRate;
  43181. }
  43182. else {
  43183. this._soundSource.playbackRate.value = this._playbackRate;
  43184. }
  43185. }
  43186. }
  43187. };
  43188. Sound.prototype._createSpatialParameters = function () {
  43189. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43190. if (this._scene.headphone) {
  43191. this._panningModel = "HRTF";
  43192. }
  43193. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  43194. this._updateSpatialParameters();
  43195. this._soundPanner.connect(this._ouputAudioNode);
  43196. this._inputAudioNode = this._soundPanner;
  43197. }
  43198. };
  43199. Sound.prototype._updateSpatialParameters = function () {
  43200. if (this.spatialSound) {
  43201. if (this.useCustomAttenuation) {
  43202. // Tricks to disable in a way embedded Web Audio attenuation
  43203. this._soundPanner.distanceModel = "linear";
  43204. this._soundPanner.maxDistance = Number.MAX_VALUE;
  43205. this._soundPanner.refDistance = 1;
  43206. this._soundPanner.rolloffFactor = 1;
  43207. this._soundPanner.panningModel = this._panningModel;
  43208. }
  43209. else {
  43210. this._soundPanner.distanceModel = this.distanceModel;
  43211. this._soundPanner.maxDistance = this.maxDistance;
  43212. this._soundPanner.refDistance = this.refDistance;
  43213. this._soundPanner.rolloffFactor = this.rolloffFactor;
  43214. this._soundPanner.panningModel = this._panningModel;
  43215. }
  43216. }
  43217. };
  43218. Sound.prototype.switchPanningModelToHRTF = function () {
  43219. this._panningModel = "HRTF";
  43220. this._switchPanningModel();
  43221. };
  43222. Sound.prototype.switchPanningModelToEqualPower = function () {
  43223. this._panningModel = "equalpower";
  43224. this._switchPanningModel();
  43225. };
  43226. Sound.prototype._switchPanningModel = function () {
  43227. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  43228. this._soundPanner.panningModel = this._panningModel;
  43229. }
  43230. };
  43231. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  43232. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43233. if (this._isOutputConnected) {
  43234. this._ouputAudioNode.disconnect();
  43235. }
  43236. this._ouputAudioNode.connect(soundTrackAudioNode);
  43237. this._isOutputConnected = true;
  43238. }
  43239. };
  43240. /**
  43241. * Transform this sound into a directional source
  43242. * @param coneInnerAngle Size of the inner cone in degree
  43243. * @param coneOuterAngle Size of the outer cone in degree
  43244. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  43245. */
  43246. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  43247. if (coneOuterAngle < coneInnerAngle) {
  43248. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  43249. return;
  43250. }
  43251. this._coneInnerAngle = coneInnerAngle;
  43252. this._coneOuterAngle = coneOuterAngle;
  43253. this._coneOuterGain = coneOuterGain;
  43254. this._isDirectional = true;
  43255. if (this.isPlaying && this.loop) {
  43256. this.stop();
  43257. this.play();
  43258. }
  43259. };
  43260. Sound.prototype.setPosition = function (newPosition) {
  43261. this._position = newPosition;
  43262. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  43263. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  43264. }
  43265. };
  43266. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  43267. this._localDirection = newLocalDirection;
  43268. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  43269. this._updateDirection();
  43270. }
  43271. };
  43272. Sound.prototype._updateDirection = function () {
  43273. var mat = this._connectedMesh.getWorldMatrix();
  43274. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  43275. direction.normalize();
  43276. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  43277. };
  43278. Sound.prototype.updateDistanceFromListener = function () {
  43279. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  43280. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  43281. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  43282. }
  43283. };
  43284. Sound.prototype.setAttenuationFunction = function (callback) {
  43285. this._customAttenuationFunction = callback;
  43286. };
  43287. /**
  43288. * Play the sound
  43289. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  43290. * @param offset (optional) Start the sound setting it at a specific time
  43291. */
  43292. Sound.prototype.play = function (time, offset) {
  43293. var _this = this;
  43294. if (this._isReadyToPlay && this._scene.audioEnabled) {
  43295. try {
  43296. if (this._startOffset < 0) {
  43297. time = -this._startOffset;
  43298. this._startOffset = 0;
  43299. }
  43300. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  43301. if (!this._soundSource || !this._streamingSource) {
  43302. if (this.spatialSound) {
  43303. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  43304. if (this._isDirectional) {
  43305. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  43306. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  43307. this._soundPanner.coneOuterGain = this._coneOuterGain;
  43308. if (this._connectedMesh) {
  43309. this._updateDirection();
  43310. }
  43311. else {
  43312. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  43313. }
  43314. }
  43315. }
  43316. }
  43317. if (this._streaming) {
  43318. if (!this._streamingSource) {
  43319. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  43320. this._htmlAudioElement.onended = function () { _this._onended(); };
  43321. this._htmlAudioElement.playbackRate = this._playbackRate;
  43322. }
  43323. this._streamingSource.disconnect();
  43324. this._streamingSource.connect(this._inputAudioNode);
  43325. this._htmlAudioElement.play();
  43326. }
  43327. else {
  43328. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  43329. this._soundSource.buffer = this._audioBuffer;
  43330. this._soundSource.connect(this._inputAudioNode);
  43331. this._soundSource.loop = this.loop;
  43332. this._soundSource.playbackRate.value = this._playbackRate;
  43333. this._soundSource.onended = function () { _this._onended(); };
  43334. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  43335. }
  43336. this._startTime = startTime;
  43337. this.isPlaying = true;
  43338. this.isPaused = false;
  43339. }
  43340. catch (ex) {
  43341. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  43342. }
  43343. }
  43344. };
  43345. Sound.prototype._onended = function () {
  43346. this.isPlaying = false;
  43347. if (this.onended) {
  43348. this.onended();
  43349. }
  43350. };
  43351. /**
  43352. * Stop the sound
  43353. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  43354. */
  43355. Sound.prototype.stop = function (time) {
  43356. if (this.isPlaying) {
  43357. if (this._streaming) {
  43358. this._htmlAudioElement.pause();
  43359. // Test needed for Firefox or it will generate an Invalid State Error
  43360. if (this._htmlAudioElement.currentTime > 0) {
  43361. this._htmlAudioElement.currentTime = 0;
  43362. }
  43363. }
  43364. else {
  43365. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  43366. this._soundSource.stop(stopTime);
  43367. this._soundSource.onended = null;
  43368. if (!this.isPaused) {
  43369. this._startOffset = 0;
  43370. }
  43371. }
  43372. this.isPlaying = false;
  43373. }
  43374. };
  43375. Sound.prototype.pause = function () {
  43376. if (this.isPlaying) {
  43377. this.isPaused = true;
  43378. if (this._streaming) {
  43379. this._htmlAudioElement.pause();
  43380. }
  43381. else {
  43382. this.stop(0);
  43383. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  43384. }
  43385. }
  43386. };
  43387. Sound.prototype.setVolume = function (newVolume, time) {
  43388. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43389. if (time) {
  43390. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  43391. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  43392. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  43393. }
  43394. else {
  43395. this._soundGain.gain.value = newVolume;
  43396. }
  43397. }
  43398. this._volume = newVolume;
  43399. };
  43400. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  43401. this._playbackRate = newPlaybackRate;
  43402. if (this.isPlaying) {
  43403. if (this._streaming) {
  43404. this._htmlAudioElement.playbackRate = this._playbackRate;
  43405. }
  43406. else {
  43407. this._soundSource.playbackRate.value = this._playbackRate;
  43408. }
  43409. }
  43410. };
  43411. Sound.prototype.getVolume = function () {
  43412. return this._volume;
  43413. };
  43414. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  43415. var _this = this;
  43416. if (this._connectedMesh) {
  43417. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43418. this._registerFunc = null;
  43419. }
  43420. this._connectedMesh = meshToConnectTo;
  43421. if (!this.spatialSound) {
  43422. this.spatialSound = true;
  43423. this._createSpatialParameters();
  43424. if (this.isPlaying && this.loop) {
  43425. this.stop();
  43426. this.play();
  43427. }
  43428. }
  43429. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  43430. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  43431. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  43432. };
  43433. Sound.prototype.detachFromMesh = function () {
  43434. if (this._connectedMesh) {
  43435. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43436. this._registerFunc = null;
  43437. this._connectedMesh = null;
  43438. }
  43439. };
  43440. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  43441. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  43442. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  43443. this._updateDirection();
  43444. }
  43445. };
  43446. Sound.prototype.clone = function () {
  43447. var _this = this;
  43448. if (!this._streaming) {
  43449. var setBufferAndRun = function () {
  43450. if (_this._isReadyToPlay) {
  43451. clonedSound._audioBuffer = _this.getAudioBuffer();
  43452. clonedSound._isReadyToPlay = true;
  43453. if (clonedSound.autoplay) {
  43454. clonedSound.play();
  43455. }
  43456. }
  43457. else {
  43458. window.setTimeout(setBufferAndRun, 300);
  43459. }
  43460. };
  43461. var currentOptions = {
  43462. autoplay: this.autoplay, loop: this.loop,
  43463. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  43464. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  43465. refDistance: this.refDistance, distanceModel: this.distanceModel
  43466. };
  43467. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  43468. if (this.useCustomAttenuation) {
  43469. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  43470. }
  43471. clonedSound.setPosition(this._position);
  43472. clonedSound.setPlaybackRate(this._playbackRate);
  43473. setBufferAndRun();
  43474. return clonedSound;
  43475. }
  43476. else {
  43477. return null;
  43478. }
  43479. };
  43480. Sound.prototype.getAudioBuffer = function () {
  43481. return this._audioBuffer;
  43482. };
  43483. Sound.prototype.serialize = function () {
  43484. var serializationObject = {
  43485. name: this.name,
  43486. url: this.name,
  43487. autoplay: this.autoplay,
  43488. loop: this.loop,
  43489. volume: this._volume,
  43490. spatialSound: this.spatialSound,
  43491. maxDistance: this.maxDistance,
  43492. rolloffFactor: this.rolloffFactor,
  43493. refDistance: this.refDistance,
  43494. distanceModel: this.distanceModel,
  43495. playbackRate: this._playbackRate,
  43496. panningModel: this._panningModel,
  43497. soundTrackId: this.soundTrackId
  43498. };
  43499. if (this.spatialSound) {
  43500. if (this._connectedMesh)
  43501. serializationObject.connectedMeshId = this._connectedMesh.id;
  43502. serializationObject.position = this._position.asArray();
  43503. serializationObject.refDistance = this.refDistance;
  43504. serializationObject.distanceModel = this.distanceModel;
  43505. serializationObject.isDirectional = this._isDirectional;
  43506. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  43507. serializationObject.coneInnerAngle = this._coneInnerAngle;
  43508. serializationObject.coneOuterAngle = this._coneOuterAngle;
  43509. serializationObject.coneOuterGain = this._coneOuterGain;
  43510. }
  43511. return serializationObject;
  43512. };
  43513. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  43514. var soundName = parsedSound.name;
  43515. var soundUrl;
  43516. if (parsedSound.url) {
  43517. soundUrl = rootUrl + parsedSound.url;
  43518. }
  43519. else {
  43520. soundUrl = rootUrl + soundName;
  43521. }
  43522. var options = {
  43523. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  43524. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  43525. rolloffFactor: parsedSound.rolloffFactor,
  43526. refDistance: parsedSound.refDistance,
  43527. distanceModel: parsedSound.distanceModel,
  43528. playbackRate: parsedSound.playbackRate
  43529. };
  43530. var newSound;
  43531. if (!sourceSound) {
  43532. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  43533. scene._addPendingData(newSound);
  43534. }
  43535. else {
  43536. var setBufferAndRun = function () {
  43537. if (sourceSound._isReadyToPlay) {
  43538. newSound._audioBuffer = sourceSound.getAudioBuffer();
  43539. newSound._isReadyToPlay = true;
  43540. if (newSound.autoplay) {
  43541. newSound.play();
  43542. }
  43543. }
  43544. else {
  43545. window.setTimeout(setBufferAndRun, 300);
  43546. }
  43547. };
  43548. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  43549. setBufferAndRun();
  43550. }
  43551. if (parsedSound.position) {
  43552. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  43553. newSound.setPosition(soundPosition);
  43554. }
  43555. if (parsedSound.isDirectional) {
  43556. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  43557. if (parsedSound.localDirectionToMesh) {
  43558. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  43559. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  43560. }
  43561. }
  43562. if (parsedSound.connectedMeshId) {
  43563. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  43564. if (connectedMesh) {
  43565. newSound.attachToMesh(connectedMesh);
  43566. }
  43567. }
  43568. return newSound;
  43569. };
  43570. return Sound;
  43571. }());
  43572. BABYLON.Sound = Sound;
  43573. })(BABYLON || (BABYLON = {}));
  43574. //# sourceMappingURL=babylon.sound.js.map
  43575. var BABYLON;
  43576. (function (BABYLON) {
  43577. var SoundTrack = (function () {
  43578. function SoundTrack(scene, options) {
  43579. this.id = -1;
  43580. this._isMainTrack = false;
  43581. this._isInitialized = false;
  43582. this._scene = scene;
  43583. this.soundCollection = new Array();
  43584. this._options = options;
  43585. if (!this._isMainTrack) {
  43586. this._scene.soundTracks.push(this);
  43587. this.id = this._scene.soundTracks.length - 1;
  43588. }
  43589. }
  43590. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  43591. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43592. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  43593. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  43594. if (this._options) {
  43595. if (this._options.volume) {
  43596. this._outputAudioNode.gain.value = this._options.volume;
  43597. }
  43598. if (this._options.mainTrack) {
  43599. this._isMainTrack = this._options.mainTrack;
  43600. }
  43601. }
  43602. this._isInitialized = true;
  43603. }
  43604. };
  43605. SoundTrack.prototype.dispose = function () {
  43606. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43607. if (this._connectedAnalyser) {
  43608. this._connectedAnalyser.stopDebugCanvas();
  43609. }
  43610. while (this.soundCollection.length) {
  43611. this.soundCollection[0].dispose();
  43612. }
  43613. if (this._outputAudioNode) {
  43614. this._outputAudioNode.disconnect();
  43615. }
  43616. this._outputAudioNode = null;
  43617. }
  43618. };
  43619. SoundTrack.prototype.AddSound = function (sound) {
  43620. if (!this._isInitialized) {
  43621. this._initializeSoundTrackAudioGraph();
  43622. }
  43623. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43624. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  43625. }
  43626. if (sound.soundTrackId) {
  43627. if (sound.soundTrackId === -1) {
  43628. this._scene.mainSoundTrack.RemoveSound(sound);
  43629. }
  43630. else {
  43631. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  43632. }
  43633. }
  43634. this.soundCollection.push(sound);
  43635. sound.soundTrackId = this.id;
  43636. };
  43637. SoundTrack.prototype.RemoveSound = function (sound) {
  43638. var index = this.soundCollection.indexOf(sound);
  43639. if (index !== -1) {
  43640. this.soundCollection.splice(index, 1);
  43641. }
  43642. };
  43643. SoundTrack.prototype.setVolume = function (newVolume) {
  43644. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43645. this._outputAudioNode.gain.value = newVolume;
  43646. }
  43647. };
  43648. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  43649. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43650. for (var i = 0; i < this.soundCollection.length; i++) {
  43651. this.soundCollection[i].switchPanningModelToHRTF();
  43652. }
  43653. }
  43654. };
  43655. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  43656. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43657. for (var i = 0; i < this.soundCollection.length; i++) {
  43658. this.soundCollection[i].switchPanningModelToEqualPower();
  43659. }
  43660. }
  43661. };
  43662. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  43663. if (this._connectedAnalyser) {
  43664. this._connectedAnalyser.stopDebugCanvas();
  43665. }
  43666. this._connectedAnalyser = analyser;
  43667. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43668. this._outputAudioNode.disconnect();
  43669. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  43670. }
  43671. };
  43672. return SoundTrack;
  43673. }());
  43674. BABYLON.SoundTrack = SoundTrack;
  43675. })(BABYLON || (BABYLON = {}));
  43676. //# sourceMappingURL=babylon.soundtrack.js.map
  43677. var BABYLON;
  43678. (function (BABYLON) {
  43679. var Analyser = (function () {
  43680. function Analyser(scene) {
  43681. this.SMOOTHING = 0.75;
  43682. this.FFT_SIZE = 512;
  43683. this.BARGRAPHAMPLITUDE = 256;
  43684. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  43685. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  43686. this._scene = scene;
  43687. this._audioEngine = BABYLON.Engine.audioEngine;
  43688. if (this._audioEngine.canUseWebAudio) {
  43689. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  43690. this._webAudioAnalyser.minDecibels = -140;
  43691. this._webAudioAnalyser.maxDecibels = 0;
  43692. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  43693. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  43694. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  43695. }
  43696. }
  43697. Analyser.prototype.getFrequencyBinCount = function () {
  43698. if (this._audioEngine.canUseWebAudio) {
  43699. return this._webAudioAnalyser.frequencyBinCount;
  43700. }
  43701. else {
  43702. return 0;
  43703. }
  43704. };
  43705. Analyser.prototype.getByteFrequencyData = function () {
  43706. if (this._audioEngine.canUseWebAudio) {
  43707. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  43708. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  43709. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  43710. }
  43711. return this._byteFreqs;
  43712. };
  43713. Analyser.prototype.getByteTimeDomainData = function () {
  43714. if (this._audioEngine.canUseWebAudio) {
  43715. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  43716. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  43717. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  43718. }
  43719. return this._byteTime;
  43720. };
  43721. Analyser.prototype.getFloatFrequencyData = function () {
  43722. if (this._audioEngine.canUseWebAudio) {
  43723. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  43724. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  43725. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  43726. }
  43727. return this._floatFreqs;
  43728. };
  43729. Analyser.prototype.drawDebugCanvas = function () {
  43730. var _this = this;
  43731. if (this._audioEngine.canUseWebAudio) {
  43732. if (!this._debugCanvas) {
  43733. this._debugCanvas = document.createElement("canvas");
  43734. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  43735. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  43736. this._debugCanvas.style.position = "absolute";
  43737. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  43738. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  43739. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  43740. document.body.appendChild(this._debugCanvas);
  43741. this._registerFunc = function () {
  43742. _this.drawDebugCanvas();
  43743. };
  43744. this._scene.registerBeforeRender(this._registerFunc);
  43745. }
  43746. if (this._registerFunc) {
  43747. var workingArray = this.getByteFrequencyData();
  43748. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  43749. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  43750. // Draw the frequency domain chart.
  43751. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  43752. var value = workingArray[i];
  43753. var percent = value / this.BARGRAPHAMPLITUDE;
  43754. var height = this.DEBUGCANVASSIZE.height * percent;
  43755. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  43756. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  43757. var hue = i / this.getFrequencyBinCount() * 360;
  43758. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  43759. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  43760. }
  43761. }
  43762. }
  43763. };
  43764. Analyser.prototype.stopDebugCanvas = function () {
  43765. if (this._debugCanvas) {
  43766. this._scene.unregisterBeforeRender(this._registerFunc);
  43767. this._registerFunc = null;
  43768. document.body.removeChild(this._debugCanvas);
  43769. this._debugCanvas = null;
  43770. this._debugCanvasContext = null;
  43771. }
  43772. };
  43773. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  43774. if (this._audioEngine.canUseWebAudio) {
  43775. inputAudioNode.connect(this._webAudioAnalyser);
  43776. this._webAudioAnalyser.connect(outputAudioNode);
  43777. }
  43778. };
  43779. Analyser.prototype.dispose = function () {
  43780. if (this._audioEngine.canUseWebAudio) {
  43781. this._webAudioAnalyser.disconnect();
  43782. }
  43783. };
  43784. return Analyser;
  43785. }());
  43786. BABYLON.Analyser = Analyser;
  43787. })(BABYLON || (BABYLON = {}));
  43788. //# sourceMappingURL=babylon.analyser.js.map
  43789. var BABYLON;
  43790. (function (BABYLON) {
  43791. var CubeTexture = (function (_super) {
  43792. __extends(CubeTexture, _super);
  43793. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered) {
  43794. if (onLoad === void 0) { onLoad = null; }
  43795. if (onError === void 0) { onError = null; }
  43796. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  43797. if (prefiltered === void 0) { prefiltered = false; }
  43798. var _this = _super.call(this, scene) || this;
  43799. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  43800. _this.name = rootUrl;
  43801. _this.url = rootUrl;
  43802. _this._noMipmap = noMipmap;
  43803. _this.hasAlpha = false;
  43804. _this._format = format;
  43805. _this._prefiltered = prefiltered;
  43806. _this.isCube = true;
  43807. _this._textureMatrix = BABYLON.Matrix.Identity();
  43808. if (prefiltered) {
  43809. _this.gammaSpace = false;
  43810. }
  43811. if (!rootUrl && !files) {
  43812. return _this;
  43813. }
  43814. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  43815. if (!files) {
  43816. if (!extensions) {
  43817. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  43818. }
  43819. files = [];
  43820. for (var index = 0; index < extensions.length; index++) {
  43821. files.push(rootUrl + extensions[index]);
  43822. }
  43823. _this._extensions = extensions;
  43824. }
  43825. _this._files = files;
  43826. if (!_this._texture) {
  43827. if (!scene.useDelayedTextureLoading) {
  43828. if (prefiltered) {
  43829. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format);
  43830. }
  43831. else {
  43832. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  43833. }
  43834. }
  43835. else {
  43836. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43837. }
  43838. }
  43839. else if (onLoad) {
  43840. if (_this._texture.isReady) {
  43841. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  43842. }
  43843. else {
  43844. _this._texture.onLoadedCallbacks.push(onLoad);
  43845. }
  43846. }
  43847. return _this;
  43848. }
  43849. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  43850. return new CubeTexture("", scene, null, noMipmap, files);
  43851. };
  43852. CubeTexture.CreateFromPrefilteredData = function (url, scene) {
  43853. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true);
  43854. };
  43855. // Methods
  43856. CubeTexture.prototype.delayLoad = function () {
  43857. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  43858. return;
  43859. }
  43860. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  43861. this._texture = this._getFromCache(this.url, this._noMipmap);
  43862. if (!this._texture) {
  43863. if (this._prefiltered) {
  43864. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  43865. }
  43866. else {
  43867. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  43868. }
  43869. }
  43870. };
  43871. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  43872. return this._textureMatrix;
  43873. };
  43874. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  43875. this._textureMatrix = value;
  43876. };
  43877. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  43878. var texture = BABYLON.SerializationHelper.Parse(function () {
  43879. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  43880. }, parsedTexture, scene);
  43881. // Animations
  43882. if (parsedTexture.animations) {
  43883. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  43884. var parsedAnimation = parsedTexture.animations[animationIndex];
  43885. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  43886. }
  43887. }
  43888. return texture;
  43889. };
  43890. CubeTexture.prototype.clone = function () {
  43891. var _this = this;
  43892. return BABYLON.SerializationHelper.Clone(function () {
  43893. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  43894. }, this);
  43895. };
  43896. return CubeTexture;
  43897. }(BABYLON.BaseTexture));
  43898. BABYLON.CubeTexture = CubeTexture;
  43899. })(BABYLON || (BABYLON = {}));
  43900. //# sourceMappingURL=babylon.cubeTexture.js.map
  43901. var BABYLON;
  43902. (function (BABYLON) {
  43903. var RenderTargetTexture = (function (_super) {
  43904. __extends(RenderTargetTexture, _super);
  43905. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  43906. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  43907. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43908. if (isCube === void 0) { isCube = false; }
  43909. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43910. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  43911. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  43912. if (isMulti === void 0) { isMulti = false; }
  43913. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  43914. _this.isCube = isCube;
  43915. /**
  43916. * Use this list to define the list of mesh you want to render.
  43917. */
  43918. _this.renderList = new Array();
  43919. _this.renderParticles = true;
  43920. _this.renderSprites = false;
  43921. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  43922. // Events
  43923. /**
  43924. * An event triggered when the texture is unbind.
  43925. * @type {BABYLON.Observable}
  43926. */
  43927. _this.onAfterUnbindObservable = new BABYLON.Observable();
  43928. /**
  43929. * An event triggered before rendering the texture
  43930. * @type {BABYLON.Observable}
  43931. */
  43932. _this.onBeforeRenderObservable = new BABYLON.Observable();
  43933. /**
  43934. * An event triggered after rendering the texture
  43935. * @type {BABYLON.Observable}
  43936. */
  43937. _this.onAfterRenderObservable = new BABYLON.Observable();
  43938. /**
  43939. * An event triggered after the texture clear
  43940. * @type {BABYLON.Observable}
  43941. */
  43942. _this.onClearObservable = new BABYLON.Observable();
  43943. _this._currentRefreshId = -1;
  43944. _this._refreshRate = 1;
  43945. _this._samples = 1;
  43946. scene = _this.getScene();
  43947. _this.name = name;
  43948. _this.isRenderTarget = true;
  43949. _this._size = size;
  43950. _this._generateMipMaps = generateMipMaps;
  43951. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  43952. // Rendering groups
  43953. _this._renderingManager = new BABYLON.RenderingManager(scene);
  43954. if (isMulti) {
  43955. return _this;
  43956. }
  43957. _this._renderTargetOptions = {
  43958. generateMipMaps: generateMipMaps,
  43959. type: type,
  43960. samplingMode: samplingMode,
  43961. generateDepthBuffer: generateDepthBuffer,
  43962. generateStencilBuffer: generateStencilBuffer
  43963. };
  43964. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  43965. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43966. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43967. }
  43968. if (isCube) {
  43969. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  43970. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  43971. _this._textureMatrix = BABYLON.Matrix.Identity();
  43972. }
  43973. else {
  43974. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  43975. }
  43976. return _this;
  43977. }
  43978. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  43979. get: function () {
  43980. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  43981. },
  43982. enumerable: true,
  43983. configurable: true
  43984. });
  43985. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  43986. get: function () {
  43987. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  43988. },
  43989. enumerable: true,
  43990. configurable: true
  43991. });
  43992. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  43993. get: function () {
  43994. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  43995. },
  43996. enumerable: true,
  43997. configurable: true
  43998. });
  43999. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  44000. set: function (callback) {
  44001. if (this._onAfterUnbindObserver) {
  44002. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  44003. }
  44004. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  44005. },
  44006. enumerable: true,
  44007. configurable: true
  44008. });
  44009. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  44010. set: function (callback) {
  44011. if (this._onBeforeRenderObserver) {
  44012. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  44013. }
  44014. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  44015. },
  44016. enumerable: true,
  44017. configurable: true
  44018. });
  44019. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  44020. set: function (callback) {
  44021. if (this._onAfterRenderObserver) {
  44022. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  44023. }
  44024. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  44025. },
  44026. enumerable: true,
  44027. configurable: true
  44028. });
  44029. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  44030. set: function (callback) {
  44031. if (this._onClearObserver) {
  44032. this.onClearObservable.remove(this._onClearObserver);
  44033. }
  44034. this._onClearObserver = this.onClearObservable.add(callback);
  44035. },
  44036. enumerable: true,
  44037. configurable: true
  44038. });
  44039. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  44040. get: function () {
  44041. return this._renderTargetOptions;
  44042. },
  44043. enumerable: true,
  44044. configurable: true
  44045. });
  44046. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  44047. get: function () {
  44048. return this._samples;
  44049. },
  44050. set: function (value) {
  44051. if (this._samples === value) {
  44052. return;
  44053. }
  44054. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  44055. },
  44056. enumerable: true,
  44057. configurable: true
  44058. });
  44059. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  44060. this._currentRefreshId = -1;
  44061. };
  44062. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  44063. get: function () {
  44064. return this._refreshRate;
  44065. },
  44066. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  44067. set: function (value) {
  44068. this._refreshRate = value;
  44069. this.resetRefreshCounter();
  44070. },
  44071. enumerable: true,
  44072. configurable: true
  44073. });
  44074. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  44075. if (!this._postProcessManager) {
  44076. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  44077. this._postProcesses = new Array();
  44078. }
  44079. this._postProcesses.push(postProcess);
  44080. this._postProcesses[0].autoClear = false;
  44081. };
  44082. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  44083. if (!this._postProcesses) {
  44084. return;
  44085. }
  44086. if (dispose) {
  44087. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  44088. var postProcess = _a[_i];
  44089. postProcess.dispose();
  44090. postProcess = null;
  44091. }
  44092. }
  44093. this._postProcesses = [];
  44094. };
  44095. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  44096. if (!this._postProcesses) {
  44097. return;
  44098. }
  44099. var index = this._postProcesses.indexOf(postProcess);
  44100. if (index === -1) {
  44101. return;
  44102. }
  44103. this._postProcesses.splice(index, 1);
  44104. if (this._postProcesses.length > 0) {
  44105. this._postProcesses[0].autoClear = false;
  44106. }
  44107. };
  44108. RenderTargetTexture.prototype._shouldRender = function () {
  44109. if (this._currentRefreshId === -1) {
  44110. this._currentRefreshId = 1;
  44111. return true;
  44112. }
  44113. if (this.refreshRate === this._currentRefreshId) {
  44114. this._currentRefreshId = 1;
  44115. return true;
  44116. }
  44117. this._currentRefreshId++;
  44118. return false;
  44119. };
  44120. RenderTargetTexture.prototype.isReady = function () {
  44121. if (!this.getScene().renderTargetsEnabled) {
  44122. return false;
  44123. }
  44124. return _super.prototype.isReady.call(this);
  44125. };
  44126. RenderTargetTexture.prototype.getRenderSize = function () {
  44127. return this._size;
  44128. };
  44129. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  44130. get: function () {
  44131. return true;
  44132. },
  44133. enumerable: true,
  44134. configurable: true
  44135. });
  44136. RenderTargetTexture.prototype.scale = function (ratio) {
  44137. var newSize = this._size * ratio;
  44138. this.resize(newSize);
  44139. };
  44140. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  44141. if (this.isCube) {
  44142. return this._textureMatrix;
  44143. }
  44144. return _super.prototype.getReflectionTextureMatrix.call(this);
  44145. };
  44146. RenderTargetTexture.prototype.resize = function (size) {
  44147. this.releaseInternalTexture();
  44148. if (this.isCube) {
  44149. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  44150. }
  44151. else {
  44152. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  44153. }
  44154. };
  44155. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  44156. var scene = this.getScene();
  44157. var engine = scene.getEngine();
  44158. if (this.useCameraPostProcesses !== undefined) {
  44159. useCameraPostProcess = this.useCameraPostProcesses;
  44160. }
  44161. if (this._waitingRenderList) {
  44162. this.renderList = [];
  44163. for (var index = 0; index < this._waitingRenderList.length; index++) {
  44164. var id = this._waitingRenderList[index];
  44165. this.renderList.push(scene.getMeshByID(id));
  44166. }
  44167. delete this._waitingRenderList;
  44168. }
  44169. // Is predicate defined?
  44170. if (this.renderListPredicate) {
  44171. this.renderList.splice(0); // Clear previous renderList
  44172. var sceneMeshes = this.getScene().meshes;
  44173. for (var index = 0; index < sceneMeshes.length; index++) {
  44174. var mesh = sceneMeshes[index];
  44175. if (this.renderListPredicate(mesh)) {
  44176. this.renderList.push(mesh);
  44177. }
  44178. }
  44179. }
  44180. if (this.renderList && this.renderList.length === 0) {
  44181. return;
  44182. }
  44183. // Set custom projection.
  44184. // Needs to be before binding to prevent changing the aspect ratio.
  44185. var camera;
  44186. if (this.activeCamera) {
  44187. camera = this.activeCamera;
  44188. engine.setViewport(this.activeCamera.viewport);
  44189. if (this.activeCamera !== scene.activeCamera) {
  44190. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  44191. }
  44192. }
  44193. else {
  44194. camera = scene.activeCamera;
  44195. engine.setViewport(scene.activeCamera.viewport);
  44196. }
  44197. // Prepare renderingManager
  44198. this._renderingManager.reset();
  44199. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  44200. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  44201. var sceneRenderId = scene.getRenderId();
  44202. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  44203. var mesh = currentRenderList[meshIndex];
  44204. if (mesh) {
  44205. if (!mesh.isReady()) {
  44206. // Reset _currentRefreshId
  44207. this.resetRefreshCounter();
  44208. continue;
  44209. }
  44210. mesh._preActivateForIntermediateRendering(sceneRenderId);
  44211. var isMasked = void 0;
  44212. if (!this.renderList) {
  44213. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  44214. }
  44215. else {
  44216. isMasked = false;
  44217. }
  44218. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  44219. mesh._activate(sceneRenderId);
  44220. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  44221. var subMesh = mesh.subMeshes[subIndex];
  44222. scene._activeIndices.addCount(subMesh.indexCount, false);
  44223. this._renderingManager.dispatch(subMesh);
  44224. }
  44225. }
  44226. }
  44227. }
  44228. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  44229. var particleSystem = scene.particleSystems[particleIndex];
  44230. var emitter = particleSystem.emitter;
  44231. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  44232. continue;
  44233. }
  44234. if (currentRenderList.indexOf(emitter) >= 0) {
  44235. this._renderingManager.dispatchParticles(particleSystem);
  44236. }
  44237. }
  44238. if (this.isCube) {
  44239. for (var face = 0; face < 6; face++) {
  44240. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  44241. scene.incrementRenderId();
  44242. scene.resetCachedMaterial();
  44243. }
  44244. }
  44245. else {
  44246. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  44247. }
  44248. this.onAfterUnbindObservable.notifyObservers(this);
  44249. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  44250. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  44251. }
  44252. engine.setViewport(scene.activeCamera.viewport);
  44253. scene.resetCachedMaterial();
  44254. };
  44255. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  44256. var _this = this;
  44257. var scene = this.getScene();
  44258. var engine = scene.getEngine();
  44259. // Bind
  44260. if (this._postProcessManager) {
  44261. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  44262. }
  44263. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  44264. if (this.isCube) {
  44265. engine.bindFramebuffer(this._texture, faceIndex);
  44266. }
  44267. else {
  44268. engine.bindFramebuffer(this._texture);
  44269. }
  44270. }
  44271. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  44272. // Clear
  44273. if (this.onClearObservable.hasObservers()) {
  44274. this.onClearObservable.notifyObservers(engine);
  44275. }
  44276. else {
  44277. engine.clear(scene.clearColor, true, true, true);
  44278. }
  44279. if (!this._doNotChangeAspectRatio) {
  44280. scene.updateTransformMatrix(true);
  44281. }
  44282. // Render
  44283. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  44284. if (this._postProcessManager) {
  44285. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  44286. }
  44287. else if (useCameraPostProcess) {
  44288. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  44289. }
  44290. if (!this._doNotChangeAspectRatio) {
  44291. scene.updateTransformMatrix(true);
  44292. }
  44293. // Dump ?
  44294. if (dumpForDebug) {
  44295. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  44296. }
  44297. // Unbind
  44298. if (!this.isCube || faceIndex === 5) {
  44299. if (this.isCube) {
  44300. if (faceIndex === 5) {
  44301. engine.generateMipMapsForCubemap(this._texture);
  44302. }
  44303. }
  44304. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  44305. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  44306. });
  44307. }
  44308. else {
  44309. this.onAfterRenderObservable.notifyObservers(faceIndex);
  44310. }
  44311. };
  44312. /**
  44313. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  44314. * This allowed control for front to back rendering or reversly depending of the special needs.
  44315. *
  44316. * @param renderingGroupId The rendering group id corresponding to its index
  44317. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  44318. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  44319. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  44320. */
  44321. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  44322. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  44323. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  44324. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  44325. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  44326. };
  44327. /**
  44328. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  44329. *
  44330. * @param renderingGroupId The rendering group id corresponding to its index
  44331. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  44332. */
  44333. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  44334. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  44335. };
  44336. RenderTargetTexture.prototype.clone = function () {
  44337. var textureSize = this.getSize();
  44338. 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);
  44339. // Base texture
  44340. newTexture.hasAlpha = this.hasAlpha;
  44341. newTexture.level = this.level;
  44342. // RenderTarget Texture
  44343. newTexture.coordinatesMode = this.coordinatesMode;
  44344. newTexture.renderList = this.renderList.slice(0);
  44345. return newTexture;
  44346. };
  44347. RenderTargetTexture.prototype.serialize = function () {
  44348. if (!this.name) {
  44349. return null;
  44350. }
  44351. var serializationObject = _super.prototype.serialize.call(this);
  44352. serializationObject.renderTargetSize = this.getRenderSize();
  44353. serializationObject.renderList = [];
  44354. for (var index = 0; index < this.renderList.length; index++) {
  44355. serializationObject.renderList.push(this.renderList[index].id);
  44356. }
  44357. return serializationObject;
  44358. };
  44359. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  44360. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  44361. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  44362. };
  44363. RenderTargetTexture.prototype.dispose = function () {
  44364. if (this._postProcessManager) {
  44365. this._postProcessManager.dispose();
  44366. this._postProcessManager = null;
  44367. }
  44368. this.clearPostProcesses(true);
  44369. // Remove from custom render targets
  44370. var scene = this.getScene();
  44371. var index = scene.customRenderTargets.indexOf(this);
  44372. if (index >= 0) {
  44373. scene.customRenderTargets.splice(index, 1);
  44374. }
  44375. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  44376. var camera = _a[_i];
  44377. index = camera.customRenderTargets.indexOf(this);
  44378. if (index >= 0) {
  44379. camera.customRenderTargets.splice(index, 1);
  44380. }
  44381. }
  44382. _super.prototype.dispose.call(this);
  44383. };
  44384. return RenderTargetTexture;
  44385. }(BABYLON.Texture));
  44386. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  44387. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  44388. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  44389. BABYLON.RenderTargetTexture = RenderTargetTexture;
  44390. })(BABYLON || (BABYLON = {}));
  44391. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  44392. var BABYLON;
  44393. (function (BABYLON) {
  44394. ;
  44395. var MultiRenderTarget = (function (_super) {
  44396. __extends(MultiRenderTarget, _super);
  44397. function MultiRenderTarget(name, size, count, scene, options) {
  44398. var _this = this;
  44399. options = options || {};
  44400. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  44401. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  44402. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  44403. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  44404. if (!_this.isSupported) {
  44405. _this.dispose();
  44406. return;
  44407. }
  44408. var types = [];
  44409. var samplingModes = [];
  44410. for (var i = 0; i < count; i++) {
  44411. if (options.types && options.types[i]) {
  44412. types.push(options.types[i]);
  44413. }
  44414. else {
  44415. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  44416. }
  44417. if (options.samplingModes && options.samplingModes[i]) {
  44418. samplingModes.push(options.samplingModes[i]);
  44419. }
  44420. else {
  44421. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44422. }
  44423. }
  44424. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  44425. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  44426. _this._count = count;
  44427. _this._size = size;
  44428. _this._multiRenderTargetOptions = {
  44429. samplingModes: samplingModes,
  44430. generateMipMaps: generateMipMaps,
  44431. generateDepthBuffer: generateDepthBuffer,
  44432. generateStencilBuffer: generateStencilBuffer,
  44433. generateDepthTexture: generateDepthTexture,
  44434. types: types,
  44435. textureCount: count
  44436. };
  44437. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  44438. _this._createInternalTextures();
  44439. return _this;
  44440. }
  44441. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  44442. get: function () {
  44443. var engine = this.getScene().getEngine();
  44444. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  44445. },
  44446. enumerable: true,
  44447. configurable: true
  44448. });
  44449. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  44450. get: function () {
  44451. return this._textures;
  44452. },
  44453. enumerable: true,
  44454. configurable: true
  44455. });
  44456. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  44457. get: function () {
  44458. return this._textures[this._textures.length - 1];
  44459. },
  44460. enumerable: true,
  44461. configurable: true
  44462. });
  44463. MultiRenderTarget.prototype._createInternalTextures = function () {
  44464. this._textures = [];
  44465. for (var i = 0; i < this._webGLTextures.length; i++) {
  44466. var texture = new BABYLON.Texture(null, this.getScene());
  44467. texture._texture = this._webGLTextures[i];
  44468. this._textures.push(texture);
  44469. }
  44470. // Keeps references to frame buffer and stencil/depth buffer
  44471. this._texture = this._webGLTextures[0];
  44472. };
  44473. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  44474. get: function () {
  44475. return this._samples;
  44476. },
  44477. set: function (value) {
  44478. if (this._samples === value) {
  44479. return;
  44480. }
  44481. for (var i = 0; i < this._webGLTextures.length; i++) {
  44482. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  44483. }
  44484. },
  44485. enumerable: true,
  44486. configurable: true
  44487. });
  44488. MultiRenderTarget.prototype.resize = function (size) {
  44489. this.releaseInternalTextures();
  44490. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  44491. this._createInternalTextures();
  44492. };
  44493. MultiRenderTarget.prototype.dispose = function () {
  44494. this.releaseInternalTextures();
  44495. _super.prototype.dispose.call(this);
  44496. };
  44497. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  44498. if (!this._webGLTextures) {
  44499. return;
  44500. }
  44501. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  44502. if (this._webGLTextures[i] !== undefined) {
  44503. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  44504. this._webGLTextures.splice(i, 1);
  44505. }
  44506. }
  44507. };
  44508. return MultiRenderTarget;
  44509. }(BABYLON.RenderTargetTexture));
  44510. BABYLON.MultiRenderTarget = MultiRenderTarget;
  44511. })(BABYLON || (BABYLON = {}));
  44512. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  44513. /// <reference path="babylon.renderTargetTexture.ts" />
  44514. var BABYLON;
  44515. (function (BABYLON) {
  44516. var MirrorTexture = (function (_super) {
  44517. __extends(MirrorTexture, _super);
  44518. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  44519. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44521. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  44522. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  44523. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  44524. _this._transformMatrix = BABYLON.Matrix.Zero();
  44525. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  44526. _this._blurKernelX = 0;
  44527. _this._blurKernelY = 0;
  44528. _this._blurRatio = 1.0;
  44529. _this.onBeforeRenderObservable.add(function () {
  44530. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  44531. _this._savedViewMatrix = scene.getViewMatrix();
  44532. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  44533. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  44534. scene.clipPlane = _this.mirrorPlane;
  44535. scene.getEngine().cullBackFaces = false;
  44536. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  44537. });
  44538. _this.onAfterRenderObservable.add(function () {
  44539. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  44540. scene.getEngine().cullBackFaces = true;
  44541. scene._mirroredCameraPosition = null;
  44542. delete scene.clipPlane;
  44543. });
  44544. return _this;
  44545. }
  44546. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  44547. get: function () {
  44548. return this._blurRatio;
  44549. },
  44550. set: function (value) {
  44551. if (this._blurRatio === value) {
  44552. return;
  44553. }
  44554. this._blurRatio = value;
  44555. this._preparePostProcesses();
  44556. },
  44557. enumerable: true,
  44558. configurable: true
  44559. });
  44560. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  44561. set: function (value) {
  44562. this.blurKernelX = value;
  44563. this.blurKernelY = value;
  44564. },
  44565. enumerable: true,
  44566. configurable: true
  44567. });
  44568. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  44569. get: function () {
  44570. return this._blurKernelX;
  44571. },
  44572. set: function (value) {
  44573. if (this._blurKernelX === value) {
  44574. return;
  44575. }
  44576. this._blurKernelX = value;
  44577. this._preparePostProcesses();
  44578. },
  44579. enumerable: true,
  44580. configurable: true
  44581. });
  44582. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  44583. get: function () {
  44584. return this._blurKernelY;
  44585. },
  44586. set: function (value) {
  44587. if (this._blurKernelY === value) {
  44588. return;
  44589. }
  44590. this._blurKernelY = value;
  44591. this._preparePostProcesses();
  44592. },
  44593. enumerable: true,
  44594. configurable: true
  44595. });
  44596. MirrorTexture.prototype._preparePostProcesses = function () {
  44597. this.clearPostProcesses(true);
  44598. if (this._blurKernelX && this._blurKernelY) {
  44599. var engine = this.getScene().getEngine();
  44600. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  44601. 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);
  44602. this._blurX.autoClear = false;
  44603. if (this._blurRatio === 1 && this.samples < 2) {
  44604. this._blurX.outputTexture = this._texture;
  44605. }
  44606. else {
  44607. this._blurX.alwaysForcePOT = true;
  44608. }
  44609. 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);
  44610. this._blurY.autoClear = false;
  44611. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  44612. this.addPostProcess(this._blurX);
  44613. this.addPostProcess(this._blurY);
  44614. }
  44615. };
  44616. MirrorTexture.prototype.clone = function () {
  44617. var textureSize = this.getSize();
  44618. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  44619. // Base texture
  44620. newTexture.hasAlpha = this.hasAlpha;
  44621. newTexture.level = this.level;
  44622. // Mirror Texture
  44623. newTexture.mirrorPlane = this.mirrorPlane.clone();
  44624. newTexture.renderList = this.renderList.slice(0);
  44625. return newTexture;
  44626. };
  44627. MirrorTexture.prototype.serialize = function () {
  44628. if (!this.name) {
  44629. return null;
  44630. }
  44631. var serializationObject = _super.prototype.serialize.call(this);
  44632. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  44633. return serializationObject;
  44634. };
  44635. return MirrorTexture;
  44636. }(BABYLON.RenderTargetTexture));
  44637. BABYLON.MirrorTexture = MirrorTexture;
  44638. })(BABYLON || (BABYLON = {}));
  44639. //# sourceMappingURL=babylon.mirrorTexture.js.map
  44640. /// <reference path="babylon.renderTargetTexture.ts" />
  44641. var BABYLON;
  44642. (function (BABYLON) {
  44643. /**
  44644. * Creates a refraction texture used by refraction channel of the standard material.
  44645. * @param name the texture name
  44646. * @param size size of the underlying texture
  44647. * @param scene root scene
  44648. */
  44649. var RefractionTexture = (function (_super) {
  44650. __extends(RefractionTexture, _super);
  44651. function RefractionTexture(name, size, scene, generateMipMaps) {
  44652. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  44653. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  44654. _this.depth = 2.0;
  44655. _this.onBeforeRenderObservable.add(function () {
  44656. scene.clipPlane = _this.refractionPlane;
  44657. });
  44658. _this.onAfterRenderObservable.add(function () {
  44659. delete scene.clipPlane;
  44660. });
  44661. return _this;
  44662. }
  44663. RefractionTexture.prototype.clone = function () {
  44664. var textureSize = this.getSize();
  44665. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  44666. // Base texture
  44667. newTexture.hasAlpha = this.hasAlpha;
  44668. newTexture.level = this.level;
  44669. // Refraction Texture
  44670. newTexture.refractionPlane = this.refractionPlane.clone();
  44671. newTexture.renderList = this.renderList.slice(0);
  44672. newTexture.depth = this.depth;
  44673. return newTexture;
  44674. };
  44675. RefractionTexture.prototype.serialize = function () {
  44676. if (!this.name) {
  44677. return null;
  44678. }
  44679. var serializationObject = _super.prototype.serialize.call(this);
  44680. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  44681. serializationObject.depth = this.depth;
  44682. return serializationObject;
  44683. };
  44684. return RefractionTexture;
  44685. }(BABYLON.RenderTargetTexture));
  44686. BABYLON.RefractionTexture = RefractionTexture;
  44687. })(BABYLON || (BABYLON = {}));
  44688. //# sourceMappingURL=babylon.refractionTexture.js.map
  44689. /// <reference path="babylon.texture.ts" />
  44690. var BABYLON;
  44691. (function (BABYLON) {
  44692. var DynamicTexture = (function (_super) {
  44693. __extends(DynamicTexture, _super);
  44694. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  44695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44696. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  44697. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  44698. _this.name = name;
  44699. var engine = _this.getScene().getEngine();
  44700. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44701. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44702. _this._generateMipMaps = generateMipMaps;
  44703. if (options.getContext) {
  44704. _this._canvas = options;
  44705. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  44706. }
  44707. else {
  44708. _this._canvas = document.createElement("canvas");
  44709. if (options.width) {
  44710. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  44711. }
  44712. else {
  44713. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  44714. }
  44715. }
  44716. var textureSize = _this.getSize();
  44717. _this._canvas.width = textureSize.width;
  44718. _this._canvas.height = textureSize.height;
  44719. _this._context = _this._canvas.getContext("2d");
  44720. return _this;
  44721. }
  44722. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  44723. get: function () {
  44724. return true;
  44725. },
  44726. enumerable: true,
  44727. configurable: true
  44728. });
  44729. DynamicTexture.prototype._recreate = function (textureSize) {
  44730. this._canvas.width = textureSize.width;
  44731. this._canvas.height = textureSize.height;
  44732. this.releaseInternalTexture();
  44733. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  44734. };
  44735. DynamicTexture.prototype.scale = function (ratio) {
  44736. var textureSize = this.getSize();
  44737. textureSize.width *= ratio;
  44738. textureSize.height *= ratio;
  44739. this._recreate(textureSize);
  44740. };
  44741. DynamicTexture.prototype.scaleTo = function (width, height) {
  44742. var textureSize = this.getSize();
  44743. textureSize.width = width;
  44744. textureSize.height = height;
  44745. this._recreate(textureSize);
  44746. };
  44747. DynamicTexture.prototype.getContext = function () {
  44748. return this._context;
  44749. };
  44750. DynamicTexture.prototype.clear = function () {
  44751. var size = this.getSize();
  44752. this._context.fillRect(0, 0, size.width, size.height);
  44753. };
  44754. DynamicTexture.prototype.update = function (invertY) {
  44755. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  44756. };
  44757. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  44758. if (update === void 0) { update = true; }
  44759. var size = this.getSize();
  44760. if (clearColor) {
  44761. this._context.fillStyle = clearColor;
  44762. this._context.fillRect(0, 0, size.width, size.height);
  44763. }
  44764. this._context.font = font;
  44765. if (x === null || x === undefined) {
  44766. var textSize = this._context.measureText(text);
  44767. x = (size.width - textSize.width) / 2;
  44768. }
  44769. if (y === null || y === undefined) {
  44770. var fontSize = parseInt((font.replace(/\D/g, '')));
  44771. ;
  44772. y = (size.height / 2) + (fontSize / 3.65);
  44773. }
  44774. this._context.fillStyle = color;
  44775. this._context.fillText(text, x, y);
  44776. if (update) {
  44777. this.update(invertY);
  44778. }
  44779. };
  44780. DynamicTexture.prototype.clone = function () {
  44781. var textureSize = this.getSize();
  44782. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  44783. // Base texture
  44784. newTexture.hasAlpha = this.hasAlpha;
  44785. newTexture.level = this.level;
  44786. // Dynamic Texture
  44787. newTexture.wrapU = this.wrapU;
  44788. newTexture.wrapV = this.wrapV;
  44789. return newTexture;
  44790. };
  44791. return DynamicTexture;
  44792. }(BABYLON.Texture));
  44793. BABYLON.DynamicTexture = DynamicTexture;
  44794. })(BABYLON || (BABYLON = {}));
  44795. //# sourceMappingURL=babylon.dynamicTexture.js.map
  44796. var BABYLON;
  44797. (function (BABYLON) {
  44798. var VideoTexture = (function (_super) {
  44799. __extends(VideoTexture, _super);
  44800. /**
  44801. * Creates a video texture.
  44802. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  44803. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  44804. * @param {BABYLON.Scene} scene is obviously the current scene.
  44805. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  44806. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  44807. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  44808. */
  44809. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  44810. if (generateMipMaps === void 0) { generateMipMaps = false; }
  44811. if (invertY === void 0) { invertY = false; }
  44812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44813. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  44814. _this._autoLaunch = true;
  44815. var urls;
  44816. _this.name = name;
  44817. if (urlsOrVideo instanceof HTMLVideoElement) {
  44818. _this.video = urlsOrVideo;
  44819. }
  44820. else {
  44821. urls = urlsOrVideo;
  44822. _this.video = document.createElement("video");
  44823. _this.video.autoplay = false;
  44824. _this.video.loop = true;
  44825. }
  44826. _this._generateMipMaps = generateMipMaps;
  44827. _this._samplingMode = samplingMode;
  44828. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  44829. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  44830. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  44831. }
  44832. else {
  44833. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44834. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44835. _this._generateMipMaps = false;
  44836. }
  44837. if (urls) {
  44838. _this.video.addEventListener("canplay", function () {
  44839. _this._createTexture();
  44840. });
  44841. urls.forEach(function (url) {
  44842. var source = document.createElement("source");
  44843. source.src = url;
  44844. _this.video.appendChild(source);
  44845. });
  44846. }
  44847. else {
  44848. _this._createTexture();
  44849. }
  44850. _this._lastUpdate = BABYLON.Tools.Now;
  44851. return _this;
  44852. }
  44853. VideoTexture.prototype.__setTextureReady = function () {
  44854. this._texture.isReady = true;
  44855. };
  44856. VideoTexture.prototype._createTexture = function () {
  44857. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  44858. if (this._autoLaunch) {
  44859. this._autoLaunch = false;
  44860. this.video.play();
  44861. }
  44862. this._setTextureReady = this.__setTextureReady.bind(this);
  44863. this.video.addEventListener("playing", this._setTextureReady);
  44864. };
  44865. VideoTexture.prototype.update = function () {
  44866. var now = BABYLON.Tools.Now;
  44867. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  44868. return false;
  44869. }
  44870. this._lastUpdate = now;
  44871. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  44872. return true;
  44873. };
  44874. VideoTexture.prototype.dispose = function () {
  44875. _super.prototype.dispose.call(this);
  44876. this.video.removeEventListener("playing", this._setTextureReady);
  44877. };
  44878. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  44879. var video = document.createElement("video");
  44880. var constraintsDeviceId;
  44881. if (constraints && constraints.deviceId) {
  44882. constraintsDeviceId = {
  44883. exact: constraints.deviceId
  44884. };
  44885. }
  44886. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  44887. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  44888. if (navigator.getUserMedia) {
  44889. navigator.getUserMedia({
  44890. video: {
  44891. deviceId: constraintsDeviceId,
  44892. width: {
  44893. min: (constraints && constraints.minWidth) || 256,
  44894. max: (constraints && constraints.maxWidth) || 640
  44895. },
  44896. height: {
  44897. min: (constraints && constraints.minHeight) || 256,
  44898. max: (constraints && constraints.maxHeight) || 480
  44899. }
  44900. }
  44901. }, function (stream) {
  44902. if (video.mozSrcObject !== undefined) {
  44903. video.mozSrcObject = stream;
  44904. }
  44905. else {
  44906. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  44907. }
  44908. video.play();
  44909. if (onReady) {
  44910. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  44911. }
  44912. }, function (e) {
  44913. BABYLON.Tools.Error(e.name);
  44914. });
  44915. }
  44916. };
  44917. return VideoTexture;
  44918. }(BABYLON.Texture));
  44919. BABYLON.VideoTexture = VideoTexture;
  44920. })(BABYLON || (BABYLON = {}));
  44921. //# sourceMappingURL=babylon.videoTexture.js.map
  44922. var BABYLON;
  44923. (function (BABYLON) {
  44924. var RawTexture = (function (_super) {
  44925. __extends(RawTexture, _super);
  44926. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  44927. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44928. if (invertY === void 0) { invertY = false; }
  44929. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44930. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  44931. _this.format = format;
  44932. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  44933. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44934. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44935. return _this;
  44936. }
  44937. RawTexture.prototype.update = function (data) {
  44938. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  44939. };
  44940. // Statics
  44941. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44942. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44943. if (invertY === void 0) { invertY = false; }
  44944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44945. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  44946. };
  44947. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44948. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44949. if (invertY === void 0) { invertY = false; }
  44950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44951. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44952. };
  44953. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44954. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44955. if (invertY === void 0) { invertY = false; }
  44956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44957. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44958. };
  44959. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44960. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44961. if (invertY === void 0) { invertY = false; }
  44962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44963. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  44964. };
  44965. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44966. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44967. if (invertY === void 0) { invertY = false; }
  44968. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44969. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  44970. };
  44971. return RawTexture;
  44972. }(BABYLON.Texture));
  44973. BABYLON.RawTexture = RawTexture;
  44974. })(BABYLON || (BABYLON = {}));
  44975. //# sourceMappingURL=babylon.rawTexture.js.map
  44976. var BABYLON;
  44977. (function (BABYLON) {
  44978. var PostProcess = (function () {
  44979. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  44980. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  44981. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44982. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  44983. if (blockCompilation === void 0) { blockCompilation = false; }
  44984. this.name = name;
  44985. this.width = -1;
  44986. this.height = -1;
  44987. this.autoClear = true;
  44988. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  44989. /*
  44990. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  44991. Can only be used on a single postprocess or on the last one of a chain.
  44992. */
  44993. this.enablePixelPerfectMode = false;
  44994. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  44995. this.alwaysForcePOT = false;
  44996. this.samples = 1;
  44997. this._reusable = false;
  44998. this._textures = new BABYLON.SmartArray(2);
  44999. this._currentRenderTextureInd = 0;
  45000. this._scaleRatio = new BABYLON.Vector2(1, 1);
  45001. this._texelSize = BABYLON.Vector2.Zero();
  45002. // Events
  45003. /**
  45004. * An event triggered when the postprocess is activated.
  45005. * @type {BABYLON.Observable}
  45006. */
  45007. this.onActivateObservable = new BABYLON.Observable();
  45008. /**
  45009. * An event triggered when the postprocess changes its size.
  45010. * @type {BABYLON.Observable}
  45011. */
  45012. this.onSizeChangedObservable = new BABYLON.Observable();
  45013. /**
  45014. * An event triggered when the postprocess applies its effect.
  45015. * @type {BABYLON.Observable}
  45016. */
  45017. this.onApplyObservable = new BABYLON.Observable();
  45018. /**
  45019. * An event triggered before rendering the postprocess
  45020. * @type {BABYLON.Observable}
  45021. */
  45022. this.onBeforeRenderObservable = new BABYLON.Observable();
  45023. /**
  45024. * An event triggered after rendering the postprocess
  45025. * @type {BABYLON.Observable}
  45026. */
  45027. this.onAfterRenderObservable = new BABYLON.Observable();
  45028. if (camera != null) {
  45029. this._camera = camera;
  45030. this._scene = camera.getScene();
  45031. camera.attachPostProcess(this);
  45032. this._engine = this._scene.getEngine();
  45033. }
  45034. else {
  45035. this._engine = engine;
  45036. }
  45037. this._options = options;
  45038. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  45039. this._reusable = reusable || false;
  45040. this._textureType = textureType;
  45041. this._samplers = samplers || [];
  45042. this._samplers.push("textureSampler");
  45043. this._fragmentUrl = fragmentUrl;
  45044. this._vertexUrl = vertexUrl;
  45045. this._parameters = parameters || [];
  45046. this._parameters.push("scale");
  45047. this._indexParameters = indexParameters;
  45048. if (!blockCompilation) {
  45049. this.updateEffect(defines);
  45050. }
  45051. }
  45052. Object.defineProperty(PostProcess.prototype, "onActivate", {
  45053. set: function (callback) {
  45054. if (this._onActivateObserver) {
  45055. this.onActivateObservable.remove(this._onActivateObserver);
  45056. }
  45057. this._onActivateObserver = this.onActivateObservable.add(callback);
  45058. },
  45059. enumerable: true,
  45060. configurable: true
  45061. });
  45062. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  45063. set: function (callback) {
  45064. if (this._onSizeChangedObserver) {
  45065. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  45066. }
  45067. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  45068. },
  45069. enumerable: true,
  45070. configurable: true
  45071. });
  45072. Object.defineProperty(PostProcess.prototype, "onApply", {
  45073. set: function (callback) {
  45074. if (this._onApplyObserver) {
  45075. this.onApplyObservable.remove(this._onApplyObserver);
  45076. }
  45077. this._onApplyObserver = this.onApplyObservable.add(callback);
  45078. },
  45079. enumerable: true,
  45080. configurable: true
  45081. });
  45082. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  45083. set: function (callback) {
  45084. if (this._onBeforeRenderObserver) {
  45085. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  45086. }
  45087. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  45088. },
  45089. enumerable: true,
  45090. configurable: true
  45091. });
  45092. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  45093. set: function (callback) {
  45094. if (this._onAfterRenderObserver) {
  45095. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  45096. }
  45097. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  45098. },
  45099. enumerable: true,
  45100. configurable: true
  45101. });
  45102. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  45103. get: function () {
  45104. return this._textures.data[this._currentRenderTextureInd];
  45105. },
  45106. set: function (value) {
  45107. this._forcedOutputTexture = value;
  45108. },
  45109. enumerable: true,
  45110. configurable: true
  45111. });
  45112. PostProcess.prototype.getCamera = function () {
  45113. return this._camera;
  45114. };
  45115. Object.defineProperty(PostProcess.prototype, "texelSize", {
  45116. get: function () {
  45117. if (this._shareOutputWithPostProcess) {
  45118. return this._shareOutputWithPostProcess.texelSize;
  45119. }
  45120. if (this._forcedOutputTexture) {
  45121. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  45122. }
  45123. return this._texelSize;
  45124. },
  45125. enumerable: true,
  45126. configurable: true
  45127. });
  45128. PostProcess.prototype.getEngine = function () {
  45129. return this._engine;
  45130. };
  45131. PostProcess.prototype.getEffect = function () {
  45132. return this._effect;
  45133. };
  45134. PostProcess.prototype.shareOutputWith = function (postProcess) {
  45135. this._disposeTextures();
  45136. this._shareOutputWithPostProcess = postProcess;
  45137. return this;
  45138. };
  45139. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  45140. 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);
  45141. };
  45142. PostProcess.prototype.isReusable = function () {
  45143. return this._reusable;
  45144. };
  45145. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  45146. PostProcess.prototype.markTextureDirty = function () {
  45147. this.width = -1;
  45148. };
  45149. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  45150. var _this = this;
  45151. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  45152. camera = camera || this._camera;
  45153. var scene = camera.getScene();
  45154. var engine = scene.getEngine();
  45155. var maxSize = engine.getCaps().maxTextureSize;
  45156. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  45157. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  45158. var desiredWidth = this._options.width || requiredWidth;
  45159. var desiredHeight = this._options.height || requiredHeight;
  45160. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  45161. if (!this._options.width) {
  45162. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  45163. }
  45164. if (!this._options.height) {
  45165. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  45166. }
  45167. }
  45168. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  45169. if (this._textures.length > 0) {
  45170. for (var i = 0; i < this._textures.length; i++) {
  45171. this._engine._releaseTexture(this._textures.data[i]);
  45172. }
  45173. this._textures.reset();
  45174. }
  45175. this.width = desiredWidth;
  45176. this.height = desiredHeight;
  45177. var textureSize = { width: this.width, height: this.height };
  45178. var textureOptions = {
  45179. generateMipMaps: false,
  45180. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  45181. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  45182. samplingMode: this.renderTargetSamplingMode,
  45183. type: this._textureType
  45184. };
  45185. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  45186. if (this._reusable) {
  45187. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  45188. }
  45189. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  45190. this.onSizeChangedObservable.notifyObservers(this);
  45191. }
  45192. this._textures.forEach(function (texture) {
  45193. if (texture.samples !== _this.samples) {
  45194. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  45195. }
  45196. });
  45197. }
  45198. var target;
  45199. if (this._shareOutputWithPostProcess) {
  45200. target = this._shareOutputWithPostProcess.outputTexture;
  45201. }
  45202. else if (this._forcedOutputTexture) {
  45203. target = this._forcedOutputTexture;
  45204. this.width = this._forcedOutputTexture._width;
  45205. this.height = this._forcedOutputTexture._height;
  45206. }
  45207. else {
  45208. target = this.outputTexture;
  45209. }
  45210. if (this.enablePixelPerfectMode) {
  45211. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  45212. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  45213. }
  45214. else {
  45215. this._scaleRatio.copyFromFloats(1, 1);
  45216. this._engine.bindFramebuffer(target);
  45217. }
  45218. this.onActivateObservable.notifyObservers(camera);
  45219. // Clear
  45220. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  45221. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  45222. }
  45223. if (this._reusable) {
  45224. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  45225. }
  45226. };
  45227. Object.defineProperty(PostProcess.prototype, "isSupported", {
  45228. get: function () {
  45229. return this._effect.isSupported;
  45230. },
  45231. enumerable: true,
  45232. configurable: true
  45233. });
  45234. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  45235. get: function () {
  45236. if (this._shareOutputWithPostProcess) {
  45237. return this._shareOutputWithPostProcess.aspectRatio;
  45238. }
  45239. if (this._forcedOutputTexture) {
  45240. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  45241. }
  45242. return this.width / this.height;
  45243. },
  45244. enumerable: true,
  45245. configurable: true
  45246. });
  45247. PostProcess.prototype.apply = function () {
  45248. // Check
  45249. if (!this._effect || !this._effect.isReady())
  45250. return null;
  45251. // States
  45252. this._engine.enableEffect(this._effect);
  45253. this._engine.setState(false);
  45254. this._engine.setDepthBuffer(false);
  45255. this._engine.setDepthWrite(false);
  45256. // Alpha
  45257. this._engine.setAlphaMode(this.alphaMode);
  45258. if (this.alphaConstants) {
  45259. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  45260. }
  45261. // Texture
  45262. var source;
  45263. if (this._shareOutputWithPostProcess) {
  45264. source = this._shareOutputWithPostProcess.outputTexture;
  45265. }
  45266. else if (this._forcedOutputTexture) {
  45267. source = this._forcedOutputTexture;
  45268. }
  45269. else {
  45270. source = this.outputTexture;
  45271. }
  45272. this._effect._bindTexture("textureSampler", source);
  45273. // Parameters
  45274. this._effect.setVector2("scale", this._scaleRatio);
  45275. this.onApplyObservable.notifyObservers(this._effect);
  45276. return this._effect;
  45277. };
  45278. PostProcess.prototype._disposeTextures = function () {
  45279. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  45280. return;
  45281. }
  45282. if (this._textures.length > 0) {
  45283. for (var i = 0; i < this._textures.length; i++) {
  45284. this._engine._releaseTexture(this._textures.data[i]);
  45285. }
  45286. }
  45287. this._textures.dispose();
  45288. };
  45289. PostProcess.prototype.dispose = function (camera) {
  45290. camera = camera || this._camera;
  45291. this._disposeTextures();
  45292. if (!camera) {
  45293. return;
  45294. }
  45295. camera.detachPostProcess(this);
  45296. var index = camera._postProcesses.indexOf(this);
  45297. if (index === 0 && camera._postProcesses.length > 0) {
  45298. this._camera._postProcesses[0].markTextureDirty();
  45299. }
  45300. this.onActivateObservable.clear();
  45301. this.onAfterRenderObservable.clear();
  45302. this.onApplyObservable.clear();
  45303. this.onBeforeRenderObservable.clear();
  45304. this.onSizeChangedObservable.clear();
  45305. };
  45306. return PostProcess;
  45307. }());
  45308. BABYLON.PostProcess = PostProcess;
  45309. })(BABYLON || (BABYLON = {}));
  45310. //# sourceMappingURL=babylon.postProcess.js.map
  45311. var BABYLON;
  45312. (function (BABYLON) {
  45313. var PassPostProcess = (function (_super) {
  45314. __extends(PassPostProcess, _super);
  45315. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  45316. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45317. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  45318. }
  45319. return PassPostProcess;
  45320. }(BABYLON.PostProcess));
  45321. BABYLON.PassPostProcess = PassPostProcess;
  45322. })(BABYLON || (BABYLON = {}));
  45323. //# sourceMappingURL=babylon.passPostProcess.js.map
  45324. var BABYLON;
  45325. (function (BABYLON) {
  45326. var ShadowGenerator = (function () {
  45327. /**
  45328. * Creates a ShadowGenerator object.
  45329. * A ShadowGenerator is the required tool to use the shadows.
  45330. * Each light casting shadows needs to use its own ShadowGenerator.
  45331. * Required parameters :
  45332. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  45333. * - `light`: the light object generating the shadows.
  45334. * - `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.
  45335. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  45336. */
  45337. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  45338. // Members
  45339. this._bias = 0.00005;
  45340. this._blurBoxOffset = 1;
  45341. this._blurScale = 2;
  45342. this._blurKernel = 1;
  45343. this._useKernelBlur = false;
  45344. this._filter = ShadowGenerator.FILTER_NONE;
  45345. this._darkness = 0;
  45346. this._transparencyShadow = false;
  45347. /**
  45348. * Controls the extent to which the shadows fade out at the edge of the frustum
  45349. * Used only by directionals and spots
  45350. */
  45351. this.frustumEdgeFalloff = 0;
  45352. this.forceBackFacesOnly = false;
  45353. this._lightDirection = BABYLON.Vector3.Zero();
  45354. this._viewMatrix = BABYLON.Matrix.Zero();
  45355. this._projectionMatrix = BABYLON.Matrix.Zero();
  45356. this._transformMatrix = BABYLON.Matrix.Zero();
  45357. this._worldViewProjection = BABYLON.Matrix.Zero();
  45358. this._currentFaceIndex = 0;
  45359. this._currentFaceIndexCache = 0;
  45360. this._isCube = false;
  45361. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  45362. this._mapSize = mapSize;
  45363. this._light = light;
  45364. this._scene = light.getScene();
  45365. light._shadowGenerator = this;
  45366. // Texture type fallback from float to int if not supported.
  45367. var caps = this._scene.getEngine().getCaps();
  45368. if (!useFullFloatFirst) {
  45369. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  45370. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45371. }
  45372. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  45373. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45374. }
  45375. else {
  45376. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45377. }
  45378. }
  45379. else {
  45380. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  45381. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45382. }
  45383. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  45384. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45385. }
  45386. else {
  45387. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45388. }
  45389. }
  45390. this._initializeGenerator();
  45391. }
  45392. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  45393. // Static
  45394. get: function () {
  45395. return ShadowGenerator._FILTER_NONE;
  45396. },
  45397. enumerable: true,
  45398. configurable: true
  45399. });
  45400. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  45401. get: function () {
  45402. return ShadowGenerator._FILTER_POISSONSAMPLING;
  45403. },
  45404. enumerable: true,
  45405. configurable: true
  45406. });
  45407. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  45408. get: function () {
  45409. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  45410. },
  45411. enumerable: true,
  45412. configurable: true
  45413. });
  45414. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  45415. get: function () {
  45416. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  45417. },
  45418. enumerable: true,
  45419. configurable: true
  45420. });
  45421. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  45422. get: function () {
  45423. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  45424. },
  45425. enumerable: true,
  45426. configurable: true
  45427. });
  45428. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  45429. get: function () {
  45430. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  45431. },
  45432. enumerable: true,
  45433. configurable: true
  45434. });
  45435. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  45436. get: function () {
  45437. return this._bias;
  45438. },
  45439. set: function (bias) {
  45440. this._bias = bias;
  45441. },
  45442. enumerable: true,
  45443. configurable: true
  45444. });
  45445. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  45446. get: function () {
  45447. return this._blurBoxOffset;
  45448. },
  45449. set: function (value) {
  45450. if (this._blurBoxOffset === value) {
  45451. return;
  45452. }
  45453. this._blurBoxOffset = value;
  45454. this._disposeBlurPostProcesses();
  45455. },
  45456. enumerable: true,
  45457. configurable: true
  45458. });
  45459. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  45460. get: function () {
  45461. return this._blurScale;
  45462. },
  45463. set: function (value) {
  45464. if (this._blurScale === value) {
  45465. return;
  45466. }
  45467. this._blurScale = value;
  45468. this._disposeBlurPostProcesses();
  45469. },
  45470. enumerable: true,
  45471. configurable: true
  45472. });
  45473. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  45474. get: function () {
  45475. return this._blurKernel;
  45476. },
  45477. set: function (value) {
  45478. if (this._blurKernel === value) {
  45479. return;
  45480. }
  45481. this._blurKernel = value;
  45482. this._disposeBlurPostProcesses();
  45483. },
  45484. enumerable: true,
  45485. configurable: true
  45486. });
  45487. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  45488. get: function () {
  45489. return this._useKernelBlur;
  45490. },
  45491. set: function (value) {
  45492. if (this._useKernelBlur === value) {
  45493. return;
  45494. }
  45495. this._useKernelBlur = value;
  45496. this._disposeBlurPostProcesses();
  45497. },
  45498. enumerable: true,
  45499. configurable: true
  45500. });
  45501. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  45502. get: function () {
  45503. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  45504. },
  45505. set: function (value) {
  45506. this._depthScale = value;
  45507. },
  45508. enumerable: true,
  45509. configurable: true
  45510. });
  45511. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  45512. get: function () {
  45513. return this._filter;
  45514. },
  45515. set: function (value) {
  45516. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  45517. if (this._light.needCube()) {
  45518. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  45519. this.useExponentialShadowMap = true;
  45520. return;
  45521. }
  45522. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  45523. this.useCloseExponentialShadowMap = true;
  45524. return;
  45525. }
  45526. }
  45527. if (this._filter === value) {
  45528. return;
  45529. }
  45530. this._filter = value;
  45531. this._disposeBlurPostProcesses();
  45532. this._applyFilterValues();
  45533. this._light._markMeshesAsLightDirty();
  45534. },
  45535. enumerable: true,
  45536. configurable: true
  45537. });
  45538. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  45539. get: function () {
  45540. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  45541. },
  45542. set: function (value) {
  45543. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  45544. },
  45545. enumerable: true,
  45546. configurable: true
  45547. });
  45548. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  45549. get: function () {
  45550. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  45551. return this.useExponentialShadowMap;
  45552. },
  45553. set: function (value) {
  45554. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  45555. this.useExponentialShadowMap = value;
  45556. },
  45557. enumerable: true,
  45558. configurable: true
  45559. });
  45560. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  45561. get: function () {
  45562. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  45563. return this.useBlurExponentialShadowMap;
  45564. },
  45565. set: function (value) {
  45566. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  45567. this.useBlurExponentialShadowMap = value;
  45568. },
  45569. enumerable: true,
  45570. configurable: true
  45571. });
  45572. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  45573. get: function () {
  45574. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  45575. },
  45576. set: function (value) {
  45577. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  45578. },
  45579. enumerable: true,
  45580. configurable: true
  45581. });
  45582. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  45583. get: function () {
  45584. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  45585. },
  45586. set: function (value) {
  45587. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  45588. },
  45589. enumerable: true,
  45590. configurable: true
  45591. });
  45592. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  45593. get: function () {
  45594. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  45595. },
  45596. set: function (value) {
  45597. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  45598. },
  45599. enumerable: true,
  45600. configurable: true
  45601. });
  45602. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  45603. get: function () {
  45604. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  45605. },
  45606. set: function (value) {
  45607. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  45608. },
  45609. enumerable: true,
  45610. configurable: true
  45611. });
  45612. /**
  45613. * Returns the darkness value (float).
  45614. */
  45615. ShadowGenerator.prototype.getDarkness = function () {
  45616. return this._darkness;
  45617. };
  45618. /**
  45619. * Sets the ShadowGenerator darkness value (float <= 1.0).
  45620. * Returns the ShadowGenerator.
  45621. */
  45622. ShadowGenerator.prototype.setDarkness = function (darkness) {
  45623. if (darkness >= 1.0)
  45624. this._darkness = 1.0;
  45625. else if (darkness <= 0.0)
  45626. this._darkness = 0.0;
  45627. else
  45628. this._darkness = darkness;
  45629. return this;
  45630. };
  45631. /**
  45632. * Sets the ability to have transparent shadow (boolean).
  45633. * Returns the ShadowGenerator.
  45634. */
  45635. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  45636. this._transparencyShadow = hasShadow;
  45637. return this;
  45638. };
  45639. /**
  45640. * Returns a RenderTargetTexture object : the shadow map texture.
  45641. */
  45642. ShadowGenerator.prototype.getShadowMap = function () {
  45643. return this._shadowMap;
  45644. };
  45645. /**
  45646. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  45647. */
  45648. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  45649. if (this._shadowMap2) {
  45650. return this._shadowMap2;
  45651. }
  45652. return this._shadowMap;
  45653. };
  45654. /**
  45655. * Returns the associated light object.
  45656. */
  45657. ShadowGenerator.prototype.getLight = function () {
  45658. return this._light;
  45659. };
  45660. ShadowGenerator.prototype._initializeGenerator = function () {
  45661. this._light._markMeshesAsLightDirty();
  45662. this._initializeShadowMap();
  45663. };
  45664. ShadowGenerator.prototype._initializeShadowMap = function () {
  45665. var _this = this;
  45666. // Render target
  45667. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  45668. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45669. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45670. this._shadowMap.anisotropicFilteringLevel = 1;
  45671. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45672. this._shadowMap.renderParticles = false;
  45673. // Record Face Index before render.
  45674. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  45675. _this._currentFaceIndex = faceIndex;
  45676. });
  45677. // Custom render function.
  45678. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  45679. // Blur if required afer render.
  45680. this._shadowMap.onAfterUnbindObservable.add(function () {
  45681. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  45682. return;
  45683. }
  45684. if (!_this._blurPostProcesses) {
  45685. _this._initializeBlurRTTAndPostProcesses();
  45686. }
  45687. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  45688. });
  45689. // Clear according to the chosen filter.
  45690. this._shadowMap.onClearObservable.add(function (engine) {
  45691. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  45692. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  45693. }
  45694. else {
  45695. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  45696. }
  45697. });
  45698. };
  45699. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  45700. var _this = this;
  45701. var engine = this._scene.getEngine();
  45702. var targetSize = this._mapSize / this.blurScale;
  45703. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  45704. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  45705. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45706. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45707. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45708. }
  45709. if (this.useKernelBlur) {
  45710. 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);
  45711. this._kernelBlurXPostprocess.width = targetSize;
  45712. this._kernelBlurXPostprocess.height = targetSize;
  45713. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  45714. effect.setTexture("textureSampler", _this._shadowMap);
  45715. });
  45716. 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);
  45717. this._kernelBlurXPostprocess.autoClear = false;
  45718. this._kernelBlurYPostprocess.autoClear = false;
  45719. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45720. this._kernelBlurXPostprocess.packedFloat = true;
  45721. this._kernelBlurYPostprocess.packedFloat = true;
  45722. }
  45723. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  45724. }
  45725. else {
  45726. 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);
  45727. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  45728. effect.setFloat2("screenSize", targetSize, targetSize);
  45729. effect.setTexture("textureSampler", _this._shadowMap);
  45730. });
  45731. this._boxBlurPostprocess.autoClear = false;
  45732. this._blurPostProcesses = [this._boxBlurPostprocess];
  45733. }
  45734. };
  45735. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  45736. var index;
  45737. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45738. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  45739. }
  45740. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45741. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  45742. }
  45743. if (this._transparencyShadow) {
  45744. for (index = 0; index < transparentSubMeshes.length; index++) {
  45745. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  45746. }
  45747. }
  45748. };
  45749. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  45750. var _this = this;
  45751. var mesh = subMesh.getRenderingMesh();
  45752. var scene = this._scene;
  45753. var engine = scene.getEngine();
  45754. // Culling
  45755. engine.setState(subMesh.getMaterial().backFaceCulling);
  45756. // Managing instances
  45757. var batch = mesh._getInstancesRenderList(subMesh._id);
  45758. if (batch.mustReturn) {
  45759. return;
  45760. }
  45761. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  45762. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  45763. engine.enableEffect(this._effect);
  45764. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  45765. var material = subMesh.getMaterial();
  45766. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  45767. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  45768. this._effect.setVector3("lightPosition", this.getLight().position);
  45769. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  45770. // Alpha test
  45771. if (material && material.needAlphaTesting()) {
  45772. var alphaTexture = material.getAlphaTestTexture();
  45773. if (alphaTexture) {
  45774. this._effect.setTexture("diffuseSampler", alphaTexture);
  45775. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  45776. }
  45777. }
  45778. // Bones
  45779. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45780. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45781. }
  45782. if (this.forceBackFacesOnly) {
  45783. engine.setState(true, 0, false, true);
  45784. }
  45785. // Draw
  45786. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  45787. if (this.forceBackFacesOnly) {
  45788. engine.setState(true, 0, false, false);
  45789. }
  45790. }
  45791. else {
  45792. // Need to reset refresh rate of the shadowMap
  45793. this._shadowMap.resetRefreshCounter();
  45794. }
  45795. };
  45796. ShadowGenerator.prototype._applyFilterValues = function () {
  45797. if (this.filter === ShadowGenerator.FILTER_NONE) {
  45798. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  45799. }
  45800. else {
  45801. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45802. }
  45803. };
  45804. /**
  45805. * Boolean : true when the ShadowGenerator is finally computed.
  45806. */
  45807. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  45808. var defines = [];
  45809. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45810. defines.push("#define FLOAT");
  45811. }
  45812. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  45813. defines.push("#define ESM");
  45814. }
  45815. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45816. var mesh = subMesh.getMesh();
  45817. var material = subMesh.getMaterial();
  45818. // Alpha test
  45819. if (material && material.needAlphaTesting()) {
  45820. var alphaTexture = material.getAlphaTestTexture();
  45821. if (alphaTexture) {
  45822. defines.push("#define ALPHATEST");
  45823. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45824. attribs.push(BABYLON.VertexBuffer.UVKind);
  45825. defines.push("#define UV1");
  45826. }
  45827. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45828. if (alphaTexture.coordinatesIndex === 1) {
  45829. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45830. defines.push("#define UV2");
  45831. }
  45832. }
  45833. }
  45834. }
  45835. // Bones
  45836. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45837. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45838. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45839. if (mesh.numBoneInfluencers > 4) {
  45840. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45841. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45842. }
  45843. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45844. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45845. }
  45846. else {
  45847. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45848. }
  45849. // Instances
  45850. if (useInstances) {
  45851. defines.push("#define INSTANCES");
  45852. attribs.push("world0");
  45853. attribs.push("world1");
  45854. attribs.push("world2");
  45855. attribs.push("world3");
  45856. }
  45857. // Get correct effect
  45858. var join = defines.join("\n");
  45859. if (this._cachedDefines !== join) {
  45860. this._cachedDefines = join;
  45861. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  45862. }
  45863. return this._effect.isReady();
  45864. };
  45865. /**
  45866. * This creates the defines related to the standard BJS materials.
  45867. */
  45868. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  45869. var scene = this._scene;
  45870. var light = this._light;
  45871. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  45872. return;
  45873. }
  45874. defines["SHADOW" + lightIndex] = true;
  45875. if (this.usePoissonSampling) {
  45876. defines["SHADOWPCF" + lightIndex] = true;
  45877. }
  45878. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  45879. defines["SHADOWESM" + lightIndex] = true;
  45880. }
  45881. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  45882. defines["SHADOWCLOSEESM" + lightIndex] = true;
  45883. }
  45884. if (light.needCube()) {
  45885. defines["SHADOWCUBE" + lightIndex] = true;
  45886. }
  45887. };
  45888. /**
  45889. * This binds shadow lights related to the standard BJS materials.
  45890. * It implies the unifroms available on the materials are the standard BJS ones.
  45891. */
  45892. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  45893. var light = this._light;
  45894. var scene = this._scene;
  45895. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  45896. return;
  45897. }
  45898. if (!light.needCube()) {
  45899. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  45900. }
  45901. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  45902. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  45903. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  45904. };
  45905. // Methods
  45906. /**
  45907. * Returns a Matrix object : the updated transformation matrix.
  45908. */
  45909. ShadowGenerator.prototype.getTransformMatrix = function () {
  45910. var scene = this._scene;
  45911. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  45912. return this._transformMatrix;
  45913. }
  45914. this._currentRenderID = scene.getRenderId();
  45915. this._currentFaceIndexCache = this._currentFaceIndex;
  45916. var lightPosition = this._light.position;
  45917. if (this._light.computeTransformedInformation()) {
  45918. lightPosition = this._light.transformedPosition;
  45919. }
  45920. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  45921. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  45922. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  45923. }
  45924. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  45925. this._cachedPosition = lightPosition.clone();
  45926. this._cachedDirection = this._lightDirection.clone();
  45927. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  45928. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  45929. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  45930. }
  45931. return this._transformMatrix;
  45932. };
  45933. ShadowGenerator.prototype.recreateShadowMap = function () {
  45934. // Track render list.
  45935. var renderList = this._shadowMap.renderList;
  45936. // Clean up existing data.
  45937. this._disposeRTTandPostProcesses();
  45938. // Reinitializes.
  45939. this._initializeGenerator();
  45940. // Reaffect the filter to ensure a correct fallback if necessary.
  45941. this.filter = this.filter;
  45942. // Reaffect the filter.
  45943. this._applyFilterValues();
  45944. // Reaffect Render List.
  45945. this._shadowMap.renderList = renderList;
  45946. };
  45947. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  45948. if (this._shadowMap2) {
  45949. this._shadowMap2.dispose();
  45950. this._shadowMap2 = null;
  45951. }
  45952. if (this._downSamplePostprocess) {
  45953. this._downSamplePostprocess.dispose();
  45954. this._downSamplePostprocess = null;
  45955. }
  45956. if (this._boxBlurPostprocess) {
  45957. this._boxBlurPostprocess.dispose();
  45958. this._boxBlurPostprocess = null;
  45959. }
  45960. if (this._kernelBlurXPostprocess) {
  45961. this._kernelBlurXPostprocess.dispose();
  45962. this._kernelBlurXPostprocess = null;
  45963. }
  45964. if (this._kernelBlurYPostprocess) {
  45965. this._kernelBlurYPostprocess.dispose();
  45966. this._kernelBlurYPostprocess = null;
  45967. }
  45968. this._blurPostProcesses = null;
  45969. };
  45970. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  45971. if (this._shadowMap) {
  45972. this._shadowMap.dispose();
  45973. this._shadowMap = null;
  45974. }
  45975. this._disposeBlurPostProcesses();
  45976. };
  45977. /**
  45978. * Disposes the ShadowGenerator.
  45979. * Returns nothing.
  45980. */
  45981. ShadowGenerator.prototype.dispose = function () {
  45982. this._disposeRTTandPostProcesses();
  45983. this._light._shadowGenerator = null;
  45984. this._light._markMeshesAsLightDirty();
  45985. };
  45986. /**
  45987. * Serializes the ShadowGenerator and returns a serializationObject.
  45988. */
  45989. ShadowGenerator.prototype.serialize = function () {
  45990. var serializationObject = {};
  45991. var shadowMap = this.getShadowMap();
  45992. serializationObject.lightId = this._light.id;
  45993. serializationObject.mapSize = shadowMap.getRenderSize();
  45994. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  45995. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  45996. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  45997. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  45998. serializationObject.usePoissonSampling = this.usePoissonSampling;
  45999. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  46000. serializationObject.depthScale = this.depthScale;
  46001. serializationObject.darkness = this.getDarkness();
  46002. serializationObject.blurBoxOffset = this.blurBoxOffset;
  46003. serializationObject.blurKernel = this.blurKernel;
  46004. serializationObject.blurScale = this.blurScale;
  46005. serializationObject.useKernelBlur = this.useKernelBlur;
  46006. serializationObject.transparencyShadow = this._transparencyShadow;
  46007. serializationObject.renderList = [];
  46008. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  46009. var mesh = shadowMap.renderList[meshIndex];
  46010. serializationObject.renderList.push(mesh.id);
  46011. }
  46012. return serializationObject;
  46013. };
  46014. /**
  46015. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  46016. */
  46017. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  46018. //casting to point light, as light is missing the position attr and typescript complains.
  46019. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  46020. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  46021. var shadowMap = shadowGenerator.getShadowMap();
  46022. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  46023. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  46024. meshes.forEach(function (mesh) {
  46025. shadowMap.renderList.push(mesh);
  46026. });
  46027. }
  46028. if (parsedShadowGenerator.usePoissonSampling) {
  46029. shadowGenerator.usePoissonSampling = true;
  46030. }
  46031. else if (parsedShadowGenerator.useExponentialShadowMap) {
  46032. shadowGenerator.useExponentialShadowMap = true;
  46033. }
  46034. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  46035. shadowGenerator.useBlurExponentialShadowMap = true;
  46036. }
  46037. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  46038. shadowGenerator.useCloseExponentialShadowMap = true;
  46039. }
  46040. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  46041. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  46042. }
  46043. else if (parsedShadowGenerator.useVarianceShadowMap) {
  46044. shadowGenerator.useExponentialShadowMap = true;
  46045. }
  46046. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  46047. shadowGenerator.useBlurExponentialShadowMap = true;
  46048. }
  46049. if (parsedShadowGenerator.depthScale) {
  46050. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  46051. }
  46052. if (parsedShadowGenerator.blurScale) {
  46053. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  46054. }
  46055. if (parsedShadowGenerator.blurBoxOffset) {
  46056. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  46057. }
  46058. if (parsedShadowGenerator.useKernelBlur) {
  46059. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  46060. }
  46061. if (parsedShadowGenerator.blurKernel) {
  46062. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  46063. }
  46064. if (parsedShadowGenerator.bias !== undefined) {
  46065. shadowGenerator.bias = parsedShadowGenerator.bias;
  46066. }
  46067. if (parsedShadowGenerator.darkness) {
  46068. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  46069. }
  46070. if (parsedShadowGenerator.transparencyShadow) {
  46071. shadowGenerator.setTransparencyShadow(true);
  46072. }
  46073. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  46074. return shadowGenerator;
  46075. };
  46076. return ShadowGenerator;
  46077. }());
  46078. ShadowGenerator._FILTER_NONE = 0;
  46079. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  46080. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  46081. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  46082. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  46083. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  46084. BABYLON.ShadowGenerator = ShadowGenerator;
  46085. })(BABYLON || (BABYLON = {}));
  46086. //# sourceMappingURL=babylon.shadowGenerator.js.map
  46087. var BABYLON;
  46088. (function (BABYLON) {
  46089. var DefaultLoadingScreen = (function () {
  46090. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  46091. if (_loadingText === void 0) { _loadingText = ""; }
  46092. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  46093. var _this = this;
  46094. this._renderingCanvas = _renderingCanvas;
  46095. this._loadingText = _loadingText;
  46096. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  46097. // Resize
  46098. this._resizeLoadingUI = function () {
  46099. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  46100. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  46101. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  46102. _this._loadingDiv.style.left = canvasRect.left + "px";
  46103. _this._loadingDiv.style.top = canvasRect.top + "px";
  46104. _this._loadingDiv.style.width = canvasRect.width + "px";
  46105. _this._loadingDiv.style.height = canvasRect.height + "px";
  46106. };
  46107. }
  46108. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  46109. if (this._loadingDiv) {
  46110. // Do not add a loading screen if there is already one
  46111. return;
  46112. }
  46113. this._loadingDiv = document.createElement("div");
  46114. this._loadingDiv.id = "babylonjsLoadingDiv";
  46115. this._loadingDiv.style.opacity = "0";
  46116. this._loadingDiv.style.transition = "opacity 1.5s ease";
  46117. // Loading text
  46118. this._loadingTextDiv = document.createElement("div");
  46119. this._loadingTextDiv.style.position = "absolute";
  46120. this._loadingTextDiv.style.left = "0";
  46121. this._loadingTextDiv.style.top = "50%";
  46122. this._loadingTextDiv.style.marginTop = "80px";
  46123. this._loadingTextDiv.style.width = "100%";
  46124. this._loadingTextDiv.style.height = "20px";
  46125. this._loadingTextDiv.style.fontFamily = "Arial";
  46126. this._loadingTextDiv.style.fontSize = "14px";
  46127. this._loadingTextDiv.style.color = "white";
  46128. this._loadingTextDiv.style.textAlign = "center";
  46129. this._loadingTextDiv.innerHTML = "Loading";
  46130. this._loadingDiv.appendChild(this._loadingTextDiv);
  46131. //set the predefined text
  46132. this._loadingTextDiv.innerHTML = this._loadingText;
  46133. // Generating keyframes
  46134. var style = document.createElement('style');
  46135. style.type = 'text/css';
  46136. 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 }";
  46137. style.innerHTML = keyFrames;
  46138. document.getElementsByTagName('head')[0].appendChild(style);
  46139. // Loading img
  46140. var imgBack = new Image();
  46141. 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";
  46142. imgBack.style.position = "absolute";
  46143. imgBack.style.left = "50%";
  46144. imgBack.style.top = "50%";
  46145. imgBack.style.marginLeft = "-60px";
  46146. imgBack.style.marginTop = "-60px";
  46147. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  46148. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  46149. imgBack.style.transformOrigin = "50% 50%";
  46150. imgBack.style.webkitTransformOrigin = "50% 50%";
  46151. this._loadingDiv.appendChild(imgBack);
  46152. this._resizeLoadingUI();
  46153. window.addEventListener("resize", this._resizeLoadingUI);
  46154. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  46155. document.body.appendChild(this._loadingDiv);
  46156. this._loadingDiv.style.opacity = "1";
  46157. };
  46158. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  46159. var _this = this;
  46160. if (!this._loadingDiv) {
  46161. return;
  46162. }
  46163. var onTransitionEnd = function () {
  46164. if (!_this._loadingDiv) {
  46165. return;
  46166. }
  46167. document.body.removeChild(_this._loadingDiv);
  46168. window.removeEventListener("resize", _this._resizeLoadingUI);
  46169. _this._loadingDiv = null;
  46170. };
  46171. this._loadingDiv.style.opacity = "0";
  46172. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  46173. };
  46174. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  46175. set: function (text) {
  46176. this._loadingText = text;
  46177. if (this._loadingTextDiv) {
  46178. this._loadingTextDiv.innerHTML = this._loadingText;
  46179. }
  46180. },
  46181. enumerable: true,
  46182. configurable: true
  46183. });
  46184. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  46185. get: function () {
  46186. return this._loadingDivBackgroundColor;
  46187. },
  46188. set: function (color) {
  46189. this._loadingDivBackgroundColor = color;
  46190. if (!this._loadingDiv) {
  46191. return;
  46192. }
  46193. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  46194. },
  46195. enumerable: true,
  46196. configurable: true
  46197. });
  46198. return DefaultLoadingScreen;
  46199. }());
  46200. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  46201. })(BABYLON || (BABYLON = {}));
  46202. //# sourceMappingURL=babylon.loadingScreen.js.map
  46203. var BABYLON;
  46204. (function (BABYLON) {
  46205. var SceneLoader = (function () {
  46206. function SceneLoader() {
  46207. }
  46208. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  46209. get: function () {
  46210. return 0;
  46211. },
  46212. enumerable: true,
  46213. configurable: true
  46214. });
  46215. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  46216. get: function () {
  46217. return 1;
  46218. },
  46219. enumerable: true,
  46220. configurable: true
  46221. });
  46222. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  46223. get: function () {
  46224. return 2;
  46225. },
  46226. enumerable: true,
  46227. configurable: true
  46228. });
  46229. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  46230. get: function () {
  46231. return 3;
  46232. },
  46233. enumerable: true,
  46234. configurable: true
  46235. });
  46236. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  46237. get: function () {
  46238. return SceneLoader._ForceFullSceneLoadingForIncremental;
  46239. },
  46240. set: function (value) {
  46241. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  46242. },
  46243. enumerable: true,
  46244. configurable: true
  46245. });
  46246. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  46247. get: function () {
  46248. return SceneLoader._ShowLoadingScreen;
  46249. },
  46250. set: function (value) {
  46251. SceneLoader._ShowLoadingScreen = value;
  46252. },
  46253. enumerable: true,
  46254. configurable: true
  46255. });
  46256. Object.defineProperty(SceneLoader, "loggingLevel", {
  46257. get: function () {
  46258. return SceneLoader._loggingLevel;
  46259. },
  46260. set: function (value) {
  46261. SceneLoader._loggingLevel = value;
  46262. },
  46263. enumerable: true,
  46264. configurable: true
  46265. });
  46266. SceneLoader._getDefaultPlugin = function () {
  46267. return SceneLoader._registeredPlugins[".babylon"];
  46268. };
  46269. SceneLoader._getPluginForExtension = function (extension) {
  46270. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  46271. if (registeredPlugin) {
  46272. return registeredPlugin;
  46273. }
  46274. return SceneLoader._getDefaultPlugin();
  46275. };
  46276. SceneLoader._getPluginForDirectLoad = function (data) {
  46277. for (var extension in SceneLoader._registeredPlugins) {
  46278. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  46279. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  46280. return SceneLoader._registeredPlugins[extension];
  46281. }
  46282. }
  46283. return SceneLoader._getDefaultPlugin();
  46284. };
  46285. SceneLoader._getPluginForFilename = function (sceneFilename) {
  46286. if (sceneFilename.name) {
  46287. sceneFilename = sceneFilename.name;
  46288. }
  46289. var dotPosition = sceneFilename.lastIndexOf(".");
  46290. var queryStringPosition = sceneFilename.indexOf("?");
  46291. if (queryStringPosition === -1) {
  46292. queryStringPosition = sceneFilename.length;
  46293. }
  46294. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  46295. return SceneLoader._getPluginForExtension(extension);
  46296. };
  46297. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  46298. SceneLoader._getDirectLoad = function (sceneFilename) {
  46299. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  46300. return sceneFilename.substr(5);
  46301. }
  46302. return null;
  46303. };
  46304. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  46305. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  46306. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  46307. var plugin = registeredPlugin.plugin;
  46308. var useArrayBuffer = registeredPlugin.isBinary;
  46309. var database;
  46310. var dataCallback = function (data) {
  46311. if (scene.isDisposed) {
  46312. onError("Scene has been disposed");
  46313. return;
  46314. }
  46315. scene.database = database;
  46316. try {
  46317. onSuccess(plugin, data);
  46318. }
  46319. catch (e) {
  46320. onError(null, e);
  46321. }
  46322. };
  46323. var manifestChecked = function (success) {
  46324. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  46325. onError(request.status + " " + request.statusText);
  46326. });
  46327. };
  46328. if (directLoad) {
  46329. dataCallback(directLoad);
  46330. return;
  46331. }
  46332. if (rootUrl.indexOf("file:") === -1) {
  46333. if (scene.getEngine().enableOfflineSupport) {
  46334. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  46335. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  46336. }
  46337. else {
  46338. manifestChecked(true);
  46339. }
  46340. }
  46341. else {
  46342. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  46343. }
  46344. };
  46345. // Public functions
  46346. SceneLoader.GetPluginForExtension = function (extension) {
  46347. return SceneLoader._getPluginForExtension(extension).plugin;
  46348. };
  46349. SceneLoader.RegisterPlugin = function (plugin) {
  46350. if (typeof plugin.extensions === "string") {
  46351. var extension = plugin.extensions;
  46352. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  46353. plugin: plugin,
  46354. isBinary: false
  46355. };
  46356. }
  46357. else {
  46358. var extensions = plugin.extensions;
  46359. Object.keys(extensions).forEach(function (extension) {
  46360. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  46361. plugin: plugin,
  46362. isBinary: extensions[extension].isBinary
  46363. };
  46364. });
  46365. }
  46366. };
  46367. /**
  46368. * Import meshes into a scene
  46369. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  46370. * @param rootUrl a string that defines the root url for scene and resources
  46371. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  46372. * @param scene the instance of BABYLON.Scene to append to
  46373. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  46374. * @param onProgress a callback with a progress event for each file being loaded
  46375. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  46376. */
  46377. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  46378. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  46379. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  46380. return;
  46381. }
  46382. var loadingToken = {};
  46383. scene._addPendingData(loadingToken);
  46384. var errorHandler = function (message, exception) {
  46385. if (onError) {
  46386. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  46387. }
  46388. scene._removePendingData(loadingToken);
  46389. };
  46390. var progressHandler = function (event) {
  46391. if (onProgress) {
  46392. onProgress(event);
  46393. }
  46394. };
  46395. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  46396. if (plugin.importMesh) {
  46397. var syncedPlugin = plugin;
  46398. var meshes = [];
  46399. var particleSystems = [];
  46400. var skeletons = [];
  46401. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  46402. return;
  46403. }
  46404. if (onSuccess) {
  46405. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  46406. onSuccess(meshes, particleSystems, skeletons);
  46407. scene._removePendingData(loadingToken);
  46408. }
  46409. }
  46410. else {
  46411. var asyncedPlugin = plugin;
  46412. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  46413. if (onSuccess) {
  46414. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  46415. onSuccess(meshes, particleSystems, skeletons);
  46416. scene._removePendingData(loadingToken);
  46417. }
  46418. }, progressHandler, errorHandler);
  46419. }
  46420. }, progressHandler, errorHandler);
  46421. };
  46422. /**
  46423. * Load a scene
  46424. * @param rootUrl a string that defines the root url for scene and resources
  46425. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  46426. * @param engine is the instance of BABYLON.Engine to use to create the scene
  46427. * @param onSuccess a callback with the scene when import succeeds
  46428. * @param onProgress a callback with a progress event for each file being loaded
  46429. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  46430. */
  46431. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  46432. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  46433. };
  46434. /**
  46435. * Append a scene
  46436. * @param rootUrl a string that defines the root url for scene and resources
  46437. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  46438. * @param scene is the instance of BABYLON.Scene to append to
  46439. * @param onSuccess a callback with the scene when import succeeds
  46440. * @param onProgress a callback with a progress event for each file being loaded
  46441. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  46442. */
  46443. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  46444. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  46445. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  46446. return;
  46447. }
  46448. if (SceneLoader.ShowLoadingScreen) {
  46449. scene.getEngine().displayLoadingUI();
  46450. }
  46451. var loadingToken = {};
  46452. scene._addPendingData(loadingToken);
  46453. var errorHandler = function (message, exception) {
  46454. if (onError) {
  46455. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  46456. }
  46457. scene._removePendingData(loadingToken);
  46458. scene.getEngine().hideLoadingUI();
  46459. };
  46460. var progressHandler = function (event) {
  46461. if (onProgress) {
  46462. onProgress(event);
  46463. }
  46464. };
  46465. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  46466. if (plugin.load) {
  46467. var syncedPlugin = plugin;
  46468. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  46469. return;
  46470. }
  46471. if (onSuccess) {
  46472. onSuccess(scene);
  46473. }
  46474. scene.loadingPluginName = plugin.name;
  46475. scene._removePendingData(loadingToken);
  46476. }
  46477. else {
  46478. var asyncedPlugin = plugin;
  46479. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  46480. if (onSuccess) {
  46481. onSuccess(scene);
  46482. }
  46483. scene.loadingPluginName = plugin.name;
  46484. scene._removePendingData(loadingToken);
  46485. }, progressHandler, errorHandler);
  46486. }
  46487. if (SceneLoader.ShowLoadingScreen) {
  46488. scene.executeWhenReady(function () {
  46489. scene.getEngine().hideLoadingUI();
  46490. });
  46491. }
  46492. }, progressHandler, errorHandler);
  46493. };
  46494. return SceneLoader;
  46495. }());
  46496. // Flags
  46497. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  46498. SceneLoader._ShowLoadingScreen = true;
  46499. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  46500. // Members
  46501. SceneLoader._registeredPlugins = {};
  46502. BABYLON.SceneLoader = SceneLoader;
  46503. ;
  46504. })(BABYLON || (BABYLON = {}));
  46505. //# sourceMappingURL=babylon.sceneLoader.js.map
  46506. var BABYLON;
  46507. (function (BABYLON) {
  46508. var Internals;
  46509. (function (Internals) {
  46510. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  46511. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  46512. var parsedMaterial = parsedData.materials[index];
  46513. if (parsedMaterial.id === id) {
  46514. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  46515. }
  46516. }
  46517. return null;
  46518. };
  46519. var isDescendantOf = function (mesh, names, hierarchyIds) {
  46520. names = (names instanceof Array) ? names : [names];
  46521. for (var i in names) {
  46522. if (mesh.name === names[i]) {
  46523. hierarchyIds.push(mesh.id);
  46524. return true;
  46525. }
  46526. }
  46527. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  46528. hierarchyIds.push(mesh.id);
  46529. return true;
  46530. }
  46531. return false;
  46532. };
  46533. var logOperation = function (operation, producer) {
  46534. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  46535. };
  46536. BABYLON.SceneLoader.RegisterPlugin({
  46537. name: "babylon.js",
  46538. extensions: ".babylon",
  46539. canDirectLoad: function (data) {
  46540. if (data.indexOf("babylon") !== -1) {
  46541. return true;
  46542. }
  46543. return false;
  46544. },
  46545. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  46546. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  46547. // when SceneLoader.debugLogging = true (default), or exception encountered.
  46548. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  46549. // and avoid problems with multiple concurrent .babylon loads.
  46550. var log = "importMesh has failed JSON parse";
  46551. try {
  46552. var parsedData = JSON.parse(data);
  46553. log = "";
  46554. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  46555. var loadedSkeletonsIds = [];
  46556. var loadedMaterialsIds = [];
  46557. var hierarchyIds = [];
  46558. var index;
  46559. var cache;
  46560. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  46561. var parsedMesh = parsedData.meshes[index];
  46562. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  46563. if (meshesNames instanceof Array) {
  46564. // Remove found mesh name from list.
  46565. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  46566. }
  46567. //Geometry?
  46568. if (parsedMesh.geometryId) {
  46569. //does the file contain geometries?
  46570. if (parsedData.geometries) {
  46571. //find the correct geometry and add it to the scene
  46572. var found = false;
  46573. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  46574. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  46575. return;
  46576. }
  46577. else {
  46578. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  46579. if (parsedGeometryData.id === parsedMesh.geometryId) {
  46580. switch (geometryType) {
  46581. case "boxes":
  46582. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  46583. break;
  46584. case "spheres":
  46585. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  46586. break;
  46587. case "cylinders":
  46588. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  46589. break;
  46590. case "toruses":
  46591. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  46592. break;
  46593. case "grounds":
  46594. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  46595. break;
  46596. case "planes":
  46597. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  46598. break;
  46599. case "torusKnots":
  46600. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  46601. break;
  46602. case "vertexData":
  46603. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  46604. break;
  46605. }
  46606. found = true;
  46607. }
  46608. });
  46609. }
  46610. });
  46611. if (!found) {
  46612. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  46613. }
  46614. }
  46615. }
  46616. // Material ?
  46617. if (parsedMesh.materialId) {
  46618. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  46619. if (!materialFound && parsedData.multiMaterials) {
  46620. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  46621. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  46622. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  46623. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  46624. var subMatId = parsedMultiMaterial.materials[matIndex];
  46625. loadedMaterialsIds.push(subMatId);
  46626. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  46627. log += "\n\tMaterial " + mat.toString(fullDetails);
  46628. }
  46629. loadedMaterialsIds.push(parsedMultiMaterial.id);
  46630. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  46631. materialFound = true;
  46632. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  46633. break;
  46634. }
  46635. }
  46636. }
  46637. if (!materialFound) {
  46638. loadedMaterialsIds.push(parsedMesh.materialId);
  46639. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  46640. if (!mat) {
  46641. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  46642. }
  46643. else {
  46644. log += "\n\tMaterial " + mat.toString(fullDetails);
  46645. }
  46646. }
  46647. }
  46648. // Skeleton ?
  46649. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  46650. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  46651. if (!skeletonAlreadyLoaded) {
  46652. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  46653. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  46654. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  46655. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  46656. skeletons.push(skeleton);
  46657. loadedSkeletonsIds.push(parsedSkeleton.id);
  46658. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  46659. }
  46660. }
  46661. }
  46662. }
  46663. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  46664. meshes.push(mesh);
  46665. log += "\n\tMesh " + mesh.toString(fullDetails);
  46666. }
  46667. }
  46668. // Connecting parents
  46669. var currentMesh;
  46670. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  46671. currentMesh = scene.meshes[index];
  46672. if (currentMesh._waitingParentId) {
  46673. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  46674. currentMesh._waitingParentId = undefined;
  46675. }
  46676. }
  46677. // freeze and compute world matrix application
  46678. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  46679. currentMesh = scene.meshes[index];
  46680. if (currentMesh._waitingFreezeWorldMatrix) {
  46681. currentMesh.freezeWorldMatrix();
  46682. currentMesh._waitingFreezeWorldMatrix = undefined;
  46683. }
  46684. else {
  46685. currentMesh.computeWorldMatrix(true);
  46686. }
  46687. }
  46688. // Particles
  46689. if (parsedData.particleSystems) {
  46690. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  46691. var parsedParticleSystem = parsedData.particleSystems[index];
  46692. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  46693. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  46694. }
  46695. }
  46696. }
  46697. return true;
  46698. }
  46699. catch (err) {
  46700. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  46701. log = null;
  46702. throw err;
  46703. }
  46704. finally {
  46705. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  46706. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  46707. }
  46708. }
  46709. },
  46710. load: function (scene, data, rootUrl) {
  46711. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  46712. // when SceneLoader.debugLogging = true (default), or exception encountered.
  46713. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  46714. // and avoid problems with multiple concurrent .babylon loads.
  46715. var log = "importScene has failed JSON parse";
  46716. try {
  46717. var parsedData = JSON.parse(data);
  46718. log = "";
  46719. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  46720. // Scene
  46721. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  46722. scene.autoClear = parsedData.autoClear;
  46723. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  46724. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  46725. if (parsedData.gravity) {
  46726. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  46727. }
  46728. // Fog
  46729. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  46730. scene.fogMode = parsedData.fogMode;
  46731. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  46732. scene.fogStart = parsedData.fogStart;
  46733. scene.fogEnd = parsedData.fogEnd;
  46734. scene.fogDensity = parsedData.fogDensity;
  46735. log += "\tFog mode for scene: ";
  46736. switch (scene.fogMode) {
  46737. // getters not compiling, so using hardcoded
  46738. case 1:
  46739. log += "exp\n";
  46740. break;
  46741. case 2:
  46742. log += "exp2\n";
  46743. break;
  46744. case 3:
  46745. log += "linear\n";
  46746. break;
  46747. }
  46748. }
  46749. //Physics
  46750. if (parsedData.physicsEnabled) {
  46751. var physicsPlugin;
  46752. if (parsedData.physicsEngine === "cannon") {
  46753. physicsPlugin = new BABYLON.CannonJSPlugin();
  46754. }
  46755. else if (parsedData.physicsEngine === "oimo") {
  46756. physicsPlugin = new BABYLON.OimoJSPlugin();
  46757. }
  46758. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  46759. //else - default engine, which is currently oimo
  46760. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  46761. scene.enablePhysics(physicsGravity, physicsPlugin);
  46762. }
  46763. // Metadata
  46764. if (parsedData.metadata !== undefined) {
  46765. scene.metadata = parsedData.metadata;
  46766. }
  46767. //collisions, if defined. otherwise, default is true
  46768. if (parsedData.collisionsEnabled != undefined) {
  46769. scene.collisionsEnabled = parsedData.collisionsEnabled;
  46770. }
  46771. scene.workerCollisions = !!parsedData.workerCollisions;
  46772. var index;
  46773. var cache;
  46774. // Lights
  46775. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  46776. var parsedLight = parsedData.lights[index];
  46777. var light = BABYLON.Light.Parse(parsedLight, scene);
  46778. log += (index === 0 ? "\n\tLights:" : "");
  46779. log += "\n\t\t" + light.toString(fullDetails);
  46780. }
  46781. // Animations
  46782. if (parsedData.animations) {
  46783. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  46784. var parsedAnimation = parsedData.animations[index];
  46785. var animation = BABYLON.Animation.Parse(parsedAnimation);
  46786. scene.animations.push(animation);
  46787. log += (index === 0 ? "\n\tAnimations:" : "");
  46788. log += "\n\t\t" + animation.toString(fullDetails);
  46789. }
  46790. }
  46791. if (parsedData.autoAnimate) {
  46792. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  46793. }
  46794. // Materials
  46795. if (parsedData.materials) {
  46796. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  46797. var parsedMaterial = parsedData.materials[index];
  46798. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  46799. log += (index === 0 ? "\n\tMaterials:" : "");
  46800. log += "\n\t\t" + mat.toString(fullDetails);
  46801. }
  46802. }
  46803. if (parsedData.multiMaterials) {
  46804. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  46805. var parsedMultiMaterial = parsedData.multiMaterials[index];
  46806. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  46807. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  46808. log += "\n\t\t" + mmat.toString(fullDetails);
  46809. }
  46810. }
  46811. // Morph targets
  46812. if (parsedData.morphTargetManagers) {
  46813. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  46814. var managerData = _a[_i];
  46815. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  46816. }
  46817. }
  46818. // Skeletons
  46819. if (parsedData.skeletons) {
  46820. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  46821. var parsedSkeleton = parsedData.skeletons[index];
  46822. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  46823. log += (index === 0 ? "\n\tSkeletons:" : "");
  46824. log += "\n\t\t" + skeleton.toString(fullDetails);
  46825. }
  46826. }
  46827. // Geometries
  46828. var geometries = parsedData.geometries;
  46829. if (geometries) {
  46830. // Boxes
  46831. var boxes = geometries.boxes;
  46832. if (boxes) {
  46833. for (index = 0, cache = boxes.length; index < cache; index++) {
  46834. var parsedBox = boxes[index];
  46835. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  46836. }
  46837. }
  46838. // Spheres
  46839. var spheres = geometries.spheres;
  46840. if (spheres) {
  46841. for (index = 0, cache = spheres.length; index < cache; index++) {
  46842. var parsedSphere = spheres[index];
  46843. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  46844. }
  46845. }
  46846. // Cylinders
  46847. var cylinders = geometries.cylinders;
  46848. if (cylinders) {
  46849. for (index = 0, cache = cylinders.length; index < cache; index++) {
  46850. var parsedCylinder = cylinders[index];
  46851. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  46852. }
  46853. }
  46854. // Toruses
  46855. var toruses = geometries.toruses;
  46856. if (toruses) {
  46857. for (index = 0, cache = toruses.length; index < cache; index++) {
  46858. var parsedTorus = toruses[index];
  46859. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  46860. }
  46861. }
  46862. // Grounds
  46863. var grounds = geometries.grounds;
  46864. if (grounds) {
  46865. for (index = 0, cache = grounds.length; index < cache; index++) {
  46866. var parsedGround = grounds[index];
  46867. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  46868. }
  46869. }
  46870. // Planes
  46871. var planes = geometries.planes;
  46872. if (planes) {
  46873. for (index = 0, cache = planes.length; index < cache; index++) {
  46874. var parsedPlane = planes[index];
  46875. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  46876. }
  46877. }
  46878. // TorusKnots
  46879. var torusKnots = geometries.torusKnots;
  46880. if (torusKnots) {
  46881. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  46882. var parsedTorusKnot = torusKnots[index];
  46883. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  46884. }
  46885. }
  46886. // VertexData
  46887. var vertexData = geometries.vertexData;
  46888. if (vertexData) {
  46889. for (index = 0, cache = vertexData.length; index < cache; index++) {
  46890. var parsedVertexData = vertexData[index];
  46891. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  46892. }
  46893. }
  46894. }
  46895. // Meshes
  46896. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  46897. var parsedMesh = parsedData.meshes[index];
  46898. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  46899. log += (index === 0 ? "\n\tMeshes:" : "");
  46900. log += "\n\t\t" + mesh.toString(fullDetails);
  46901. }
  46902. // Cameras
  46903. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  46904. var parsedCamera = parsedData.cameras[index];
  46905. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  46906. log += (index === 0 ? "\n\tCameras:" : "");
  46907. log += "\n\t\t" + camera.toString(fullDetails);
  46908. }
  46909. if (parsedData.activeCameraID) {
  46910. scene.setActiveCameraByID(parsedData.activeCameraID);
  46911. }
  46912. // Browsing all the graph to connect the dots
  46913. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  46914. var camera = scene.cameras[index];
  46915. if (camera._waitingParentId) {
  46916. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  46917. camera._waitingParentId = undefined;
  46918. }
  46919. }
  46920. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  46921. var light = scene.lights[index];
  46922. if (light._waitingParentId) {
  46923. light.parent = scene.getLastEntryByID(light._waitingParentId);
  46924. light._waitingParentId = undefined;
  46925. }
  46926. }
  46927. // Sounds
  46928. var loadedSounds = [];
  46929. var loadedSound;
  46930. if (BABYLON.AudioEngine && parsedData.sounds) {
  46931. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  46932. var parsedSound = parsedData.sounds[index];
  46933. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46934. if (!parsedSound.url)
  46935. parsedSound.url = parsedSound.name;
  46936. if (!loadedSounds[parsedSound.url]) {
  46937. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  46938. loadedSounds[parsedSound.url] = loadedSound;
  46939. }
  46940. else {
  46941. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  46942. }
  46943. }
  46944. else {
  46945. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  46946. }
  46947. }
  46948. }
  46949. loadedSounds = [];
  46950. // Connect parents & children and parse actions
  46951. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  46952. var mesh = scene.meshes[index];
  46953. if (mesh._waitingParentId) {
  46954. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  46955. mesh._waitingParentId = undefined;
  46956. }
  46957. if (mesh._waitingActions) {
  46958. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  46959. mesh._waitingActions = undefined;
  46960. }
  46961. }
  46962. // freeze world matrix application
  46963. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  46964. var currentMesh = scene.meshes[index];
  46965. if (currentMesh._waitingFreezeWorldMatrix) {
  46966. currentMesh.freezeWorldMatrix();
  46967. currentMesh._waitingFreezeWorldMatrix = undefined;
  46968. }
  46969. else {
  46970. currentMesh.computeWorldMatrix(true);
  46971. }
  46972. }
  46973. // Particles Systems
  46974. if (parsedData.particleSystems) {
  46975. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  46976. var parsedParticleSystem = parsedData.particleSystems[index];
  46977. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  46978. }
  46979. }
  46980. // Lens flares
  46981. if (parsedData.lensFlareSystems) {
  46982. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  46983. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  46984. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  46985. }
  46986. }
  46987. // Shadows
  46988. if (parsedData.shadowGenerators) {
  46989. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  46990. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  46991. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  46992. }
  46993. }
  46994. // Lights exclusions / inclusions
  46995. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  46996. var light = scene.lights[index];
  46997. // Excluded check
  46998. if (light._excludedMeshesIds.length > 0) {
  46999. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  47000. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  47001. if (excludedMesh) {
  47002. light.excludedMeshes.push(excludedMesh);
  47003. }
  47004. }
  47005. light._excludedMeshesIds = [];
  47006. }
  47007. // Included check
  47008. if (light._includedOnlyMeshesIds.length > 0) {
  47009. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  47010. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  47011. if (includedOnlyMesh) {
  47012. light.includedOnlyMeshes.push(includedOnlyMesh);
  47013. }
  47014. }
  47015. light._includedOnlyMeshesIds = [];
  47016. }
  47017. }
  47018. // Actions (scene)
  47019. if (parsedData.actions) {
  47020. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  47021. }
  47022. // Finish
  47023. return true;
  47024. }
  47025. catch (err) {
  47026. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  47027. log = null;
  47028. throw err;
  47029. }
  47030. finally {
  47031. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47032. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47033. }
  47034. }
  47035. }
  47036. });
  47037. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47038. })(BABYLON || (BABYLON = {}));
  47039. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  47040. var BABYLON;
  47041. (function (BABYLON) {
  47042. var FilesInput = (function () {
  47043. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  47044. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  47045. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  47046. this._engine = p_engine;
  47047. this._canvas = p_canvas;
  47048. this._currentScene = p_scene;
  47049. this._sceneLoadedCallback = p_sceneLoadedCallback;
  47050. this._progressCallback = p_progressCallback;
  47051. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  47052. this._textureLoadingCallback = p_textureLoadingCallback;
  47053. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  47054. }
  47055. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  47056. var _this = this;
  47057. if (p_elementToMonitor) {
  47058. this._elementToMonitor = p_elementToMonitor;
  47059. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  47060. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  47061. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  47062. }
  47063. };
  47064. FilesInput.prototype.renderFunction = function () {
  47065. if (this._additionnalRenderLoopLogicCallback) {
  47066. this._additionnalRenderLoopLogicCallback();
  47067. }
  47068. if (this._currentScene) {
  47069. if (this._textureLoadingCallback) {
  47070. var remaining = this._currentScene.getWaitingItemsCount();
  47071. if (remaining > 0) {
  47072. this._textureLoadingCallback(remaining);
  47073. }
  47074. }
  47075. this._currentScene.render();
  47076. }
  47077. };
  47078. FilesInput.prototype.drag = function (e) {
  47079. e.stopPropagation();
  47080. e.preventDefault();
  47081. };
  47082. FilesInput.prototype.drop = function (eventDrop) {
  47083. eventDrop.stopPropagation();
  47084. eventDrop.preventDefault();
  47085. this.loadFiles(eventDrop);
  47086. };
  47087. FilesInput.prototype.loadFiles = function (event) {
  47088. if (this._startingProcessingFilesCallback)
  47089. this._startingProcessingFilesCallback();
  47090. // Handling data transfer via drag'n'drop
  47091. if (event && event.dataTransfer && event.dataTransfer.files) {
  47092. this._filesToLoad = event.dataTransfer.files;
  47093. }
  47094. // Handling files from input files
  47095. if (event && event.target && event.target.files) {
  47096. this._filesToLoad = event.target.files;
  47097. }
  47098. if (this._filesToLoad && this._filesToLoad.length > 0) {
  47099. for (var i = 0; i < this._filesToLoad.length; i++) {
  47100. var name_1 = this._filesToLoad[i].name.toLowerCase();
  47101. var extension = name_1.split('.').pop();
  47102. var type = this._filesToLoad[i].type;
  47103. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  47104. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  47105. this._sceneFileToLoad = this._filesToLoad[i];
  47106. }
  47107. else {
  47108. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  47109. }
  47110. }
  47111. this.reload();
  47112. }
  47113. };
  47114. FilesInput.prototype.reload = function () {
  47115. var _this = this;
  47116. var that = this;
  47117. // If a ".babylon" file has been provided
  47118. if (this._sceneFileToLoad) {
  47119. if (this._currentScene) {
  47120. if (BABYLON.Tools.errorsCount > 0) {
  47121. BABYLON.Tools.ClearLogCache();
  47122. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  47123. }
  47124. this._engine.stopRenderLoop();
  47125. this._currentScene.dispose();
  47126. }
  47127. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  47128. that._currentScene = newScene;
  47129. // Wait for textures and shaders to be ready
  47130. that._currentScene.executeWhenReady(function () {
  47131. if (that._sceneLoadedCallback) {
  47132. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  47133. }
  47134. that._engine.runRenderLoop(function () { that.renderFunction(); });
  47135. });
  47136. }, function (progress) {
  47137. if (_this._progressCallback) {
  47138. _this._progressCallback(progress);
  47139. }
  47140. });
  47141. }
  47142. else {
  47143. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  47144. }
  47145. };
  47146. return FilesInput;
  47147. }());
  47148. FilesInput.FilesToLoad = new Array();
  47149. BABYLON.FilesInput = FilesInput;
  47150. })(BABYLON || (BABYLON = {}));
  47151. //# sourceMappingURL=babylon.filesInput.js.map
  47152. var BABYLON;
  47153. (function (BABYLON) {
  47154. /**
  47155. * This class implement a typical dictionary using a string as key and the generic type T as value.
  47156. * The underlying implementation relies on an associative array to ensure the best performances.
  47157. * The value can be anything including 'null' but except 'undefined'
  47158. */
  47159. var StringDictionary = (function () {
  47160. function StringDictionary() {
  47161. this._count = 0;
  47162. this._data = {};
  47163. }
  47164. /**
  47165. * This will clear this dictionary and copy the content from the 'source' one.
  47166. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  47167. * @param source the dictionary to take the content from and copy to this dictionary
  47168. */
  47169. StringDictionary.prototype.copyFrom = function (source) {
  47170. var _this = this;
  47171. this.clear();
  47172. source.forEach(function (t, v) { return _this.add(t, v); });
  47173. };
  47174. /**
  47175. * Get a value based from its key
  47176. * @param key the given key to get the matching value from
  47177. * @return the value if found, otherwise undefined is returned
  47178. */
  47179. StringDictionary.prototype.get = function (key) {
  47180. var val = this._data[key];
  47181. if (val !== undefined) {
  47182. return val;
  47183. }
  47184. return undefined;
  47185. };
  47186. /**
  47187. * Get a value from its key or add it if it doesn't exist.
  47188. * This method will ensure you that a given key/data will be present in the dictionary.
  47189. * @param key the given key to get the matching value from
  47190. * @param factory the factory that will create the value if the key is not present in the dictionary.
  47191. * The factory will only be invoked if there's no data for the given key.
  47192. * @return the value corresponding to the key.
  47193. */
  47194. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  47195. var val = this.get(key);
  47196. if (val !== undefined) {
  47197. return val;
  47198. }
  47199. val = factory(key);
  47200. if (val) {
  47201. this.add(key, val);
  47202. }
  47203. return val;
  47204. };
  47205. /**
  47206. * Get a value from its key if present in the dictionary otherwise add it
  47207. * @param key the key to get the value from
  47208. * @param val if there's no such key/value pair in the dictionary add it with this value
  47209. * @return the value corresponding to the key
  47210. */
  47211. StringDictionary.prototype.getOrAdd = function (key, val) {
  47212. var curVal = this.get(key);
  47213. if (curVal !== undefined) {
  47214. return curVal;
  47215. }
  47216. this.add(key, val);
  47217. return val;
  47218. };
  47219. /**
  47220. * Check if there's a given key in the dictionary
  47221. * @param key the key to check for
  47222. * @return true if the key is present, false otherwise
  47223. */
  47224. StringDictionary.prototype.contains = function (key) {
  47225. return this._data[key] !== undefined;
  47226. };
  47227. /**
  47228. * Add a new key and its corresponding value
  47229. * @param key the key to add
  47230. * @param value the value corresponding to the key
  47231. * @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
  47232. */
  47233. StringDictionary.prototype.add = function (key, value) {
  47234. if (this._data[key] !== undefined) {
  47235. return false;
  47236. }
  47237. this._data[key] = value;
  47238. ++this._count;
  47239. return true;
  47240. };
  47241. StringDictionary.prototype.set = function (key, value) {
  47242. if (this._data[key] === undefined) {
  47243. return false;
  47244. }
  47245. this._data[key] = value;
  47246. return true;
  47247. };
  47248. /**
  47249. * Get the element of the given key and remove it from the dictionary
  47250. * @param key
  47251. */
  47252. StringDictionary.prototype.getAndRemove = function (key) {
  47253. var val = this.get(key);
  47254. if (val !== undefined) {
  47255. delete this._data[key];
  47256. --this._count;
  47257. return val;
  47258. }
  47259. return null;
  47260. };
  47261. /**
  47262. * Remove a key/value from the dictionary.
  47263. * @param key the key to remove
  47264. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  47265. */
  47266. StringDictionary.prototype.remove = function (key) {
  47267. if (this.contains(key)) {
  47268. delete this._data[key];
  47269. --this._count;
  47270. return true;
  47271. }
  47272. return false;
  47273. };
  47274. /**
  47275. * Clear the whole content of the dictionary
  47276. */
  47277. StringDictionary.prototype.clear = function () {
  47278. this._data = {};
  47279. this._count = 0;
  47280. };
  47281. Object.defineProperty(StringDictionary.prototype, "count", {
  47282. get: function () {
  47283. return this._count;
  47284. },
  47285. enumerable: true,
  47286. configurable: true
  47287. });
  47288. /**
  47289. * Execute a callback on each key/val of the dictionary.
  47290. * Note that you can remove any element in this dictionary in the callback implementation
  47291. * @param callback the callback to execute on a given key/value pair
  47292. */
  47293. StringDictionary.prototype.forEach = function (callback) {
  47294. for (var cur in this._data) {
  47295. var val = this._data[cur];
  47296. callback(cur, val);
  47297. }
  47298. };
  47299. /**
  47300. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  47301. * If the callback returns null or undefined the method will iterate to the next key/value pair
  47302. * Note that you can remove any element in this dictionary in the callback implementation
  47303. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  47304. */
  47305. StringDictionary.prototype.first = function (callback) {
  47306. for (var cur in this._data) {
  47307. var val = this._data[cur];
  47308. var res = callback(cur, val);
  47309. if (res) {
  47310. return res;
  47311. }
  47312. }
  47313. return null;
  47314. };
  47315. return StringDictionary;
  47316. }());
  47317. BABYLON.StringDictionary = StringDictionary;
  47318. })(BABYLON || (BABYLON = {}));
  47319. //# sourceMappingURL=babylon.stringDictionary.js.map
  47320. var BABYLON;
  47321. (function (BABYLON) {
  47322. var Tags = (function () {
  47323. function Tags() {
  47324. }
  47325. Tags.EnableFor = function (obj) {
  47326. obj._tags = obj._tags || {};
  47327. obj.hasTags = function () {
  47328. return Tags.HasTags(obj);
  47329. };
  47330. obj.addTags = function (tagsString) {
  47331. return Tags.AddTagsTo(obj, tagsString);
  47332. };
  47333. obj.removeTags = function (tagsString) {
  47334. return Tags.RemoveTagsFrom(obj, tagsString);
  47335. };
  47336. obj.matchesTagsQuery = function (tagsQuery) {
  47337. return Tags.MatchesQuery(obj, tagsQuery);
  47338. };
  47339. };
  47340. Tags.DisableFor = function (obj) {
  47341. delete obj._tags;
  47342. delete obj.hasTags;
  47343. delete obj.addTags;
  47344. delete obj.removeTags;
  47345. delete obj.matchesTagsQuery;
  47346. };
  47347. Tags.HasTags = function (obj) {
  47348. if (!obj._tags) {
  47349. return false;
  47350. }
  47351. return !BABYLON.Tools.IsEmpty(obj._tags);
  47352. };
  47353. Tags.GetTags = function (obj, asString) {
  47354. if (asString === void 0) { asString = true; }
  47355. if (!obj._tags) {
  47356. return null;
  47357. }
  47358. if (asString) {
  47359. var tagsArray = [];
  47360. for (var tag in obj._tags) {
  47361. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  47362. tagsArray.push(tag);
  47363. }
  47364. }
  47365. return tagsArray.join(" ");
  47366. }
  47367. else {
  47368. return obj._tags;
  47369. }
  47370. };
  47371. // the tags 'true' and 'false' are reserved and cannot be used as tags
  47372. // a tag cannot start with '||', '&&', and '!'
  47373. // it cannot contain whitespaces
  47374. Tags.AddTagsTo = function (obj, tagsString) {
  47375. if (!tagsString) {
  47376. return;
  47377. }
  47378. if (typeof tagsString !== "string") {
  47379. return;
  47380. }
  47381. var tags = tagsString.split(" ");
  47382. tags.forEach(function (tag, index, array) {
  47383. Tags._AddTagTo(obj, tag);
  47384. });
  47385. };
  47386. Tags._AddTagTo = function (obj, tag) {
  47387. tag = tag.trim();
  47388. if (tag === "" || tag === "true" || tag === "false") {
  47389. return;
  47390. }
  47391. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  47392. return;
  47393. }
  47394. Tags.EnableFor(obj);
  47395. obj._tags[tag] = true;
  47396. };
  47397. Tags.RemoveTagsFrom = function (obj, tagsString) {
  47398. if (!Tags.HasTags(obj)) {
  47399. return;
  47400. }
  47401. var tags = tagsString.split(" ");
  47402. for (var t in tags) {
  47403. Tags._RemoveTagFrom(obj, tags[t]);
  47404. }
  47405. };
  47406. Tags._RemoveTagFrom = function (obj, tag) {
  47407. delete obj._tags[tag];
  47408. };
  47409. Tags.MatchesQuery = function (obj, tagsQuery) {
  47410. if (tagsQuery === undefined) {
  47411. return true;
  47412. }
  47413. if (tagsQuery === "") {
  47414. return Tags.HasTags(obj);
  47415. }
  47416. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  47417. };
  47418. return Tags;
  47419. }());
  47420. BABYLON.Tags = Tags;
  47421. })(BABYLON || (BABYLON = {}));
  47422. //# sourceMappingURL=babylon.tags.js.map
  47423. var BABYLON;
  47424. (function (BABYLON) {
  47425. var Internals;
  47426. (function (Internals) {
  47427. var AndOrNotEvaluator = (function () {
  47428. function AndOrNotEvaluator() {
  47429. }
  47430. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  47431. if (!query.match(/\([^\(\)]*\)/g)) {
  47432. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  47433. }
  47434. else {
  47435. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  47436. // remove parenthesis
  47437. r = r.slice(1, r.length - 1);
  47438. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  47439. });
  47440. }
  47441. if (query === "true") {
  47442. return true;
  47443. }
  47444. if (query === "false") {
  47445. return false;
  47446. }
  47447. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  47448. };
  47449. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  47450. evaluateCallback = evaluateCallback || (function (r) {
  47451. return r === "true" ? true : false;
  47452. });
  47453. var result;
  47454. var or = parenthesisContent.split("||");
  47455. for (var i in or) {
  47456. if (or.hasOwnProperty(i)) {
  47457. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  47458. var and = ori.split("&&");
  47459. if (and.length > 1) {
  47460. for (var j = 0; j < and.length; ++j) {
  47461. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  47462. if (andj !== "true" && andj !== "false") {
  47463. if (andj[0] === "!") {
  47464. result = !evaluateCallback(andj.substring(1));
  47465. }
  47466. else {
  47467. result = evaluateCallback(andj);
  47468. }
  47469. }
  47470. else {
  47471. result = andj === "true" ? true : false;
  47472. }
  47473. if (!result) {
  47474. ori = "false";
  47475. break;
  47476. }
  47477. }
  47478. }
  47479. if (result || ori === "true") {
  47480. result = true;
  47481. break;
  47482. }
  47483. // result equals false (or undefined)
  47484. if (ori !== "true" && ori !== "false") {
  47485. if (ori[0] === "!") {
  47486. result = !evaluateCallback(ori.substring(1));
  47487. }
  47488. else {
  47489. result = evaluateCallback(ori);
  47490. }
  47491. }
  47492. else {
  47493. result = ori === "true" ? true : false;
  47494. }
  47495. }
  47496. }
  47497. // the whole parenthesis scope is replaced by 'true' or 'false'
  47498. return result ? "true" : "false";
  47499. };
  47500. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  47501. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  47502. // remove whitespaces
  47503. r = r.replace(/[\s]/g, function () { return ""; });
  47504. return r.length % 2 ? "!" : "";
  47505. });
  47506. booleanString = booleanString.trim();
  47507. if (booleanString === "!true") {
  47508. booleanString = "false";
  47509. }
  47510. else if (booleanString === "!false") {
  47511. booleanString = "true";
  47512. }
  47513. return booleanString;
  47514. };
  47515. return AndOrNotEvaluator;
  47516. }());
  47517. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  47518. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47519. })(BABYLON || (BABYLON = {}));
  47520. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  47521. var BABYLON;
  47522. (function (BABYLON) {
  47523. var Database = (function () {
  47524. function Database(urlToScene, callbackManifestChecked) {
  47525. // Handling various flavors of prefixed version of IndexedDB
  47526. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  47527. this.callbackManifestChecked = callbackManifestChecked;
  47528. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  47529. this.db = null;
  47530. this.enableSceneOffline = false;
  47531. this.enableTexturesOffline = false;
  47532. this.manifestVersionFound = 0;
  47533. this.mustUpdateRessources = false;
  47534. this.hasReachedQuota = false;
  47535. if (!Database.IDBStorageEnabled) {
  47536. this.callbackManifestChecked(true);
  47537. }
  47538. else {
  47539. this.checkManifestFile();
  47540. }
  47541. }
  47542. Database.prototype.checkManifestFile = function () {
  47543. var _this = this;
  47544. function noManifestFile() {
  47545. that.enableSceneOffline = false;
  47546. that.enableTexturesOffline = false;
  47547. that.callbackManifestChecked(false);
  47548. }
  47549. var that = this;
  47550. var timeStampUsed = false;
  47551. var manifestURL = this.currentSceneUrl + ".manifest";
  47552. var xhr = new XMLHttpRequest();
  47553. if (navigator.onLine) {
  47554. // Adding a timestamp to by-pass browsers' cache
  47555. timeStampUsed = true;
  47556. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  47557. }
  47558. xhr.open("GET", manifestURL, true);
  47559. xhr.addEventListener("load", function () {
  47560. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  47561. try {
  47562. var manifestFile = JSON.parse(xhr.response);
  47563. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  47564. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  47565. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  47566. _this.manifestVersionFound = manifestFile.version;
  47567. }
  47568. if (_this.callbackManifestChecked) {
  47569. _this.callbackManifestChecked(true);
  47570. }
  47571. }
  47572. catch (ex) {
  47573. noManifestFile();
  47574. }
  47575. }
  47576. else {
  47577. noManifestFile();
  47578. }
  47579. }, false);
  47580. xhr.addEventListener("error", function (event) {
  47581. if (timeStampUsed) {
  47582. timeStampUsed = false;
  47583. // Let's retry without the timeStamp
  47584. // It could fail when coupled with HTML5 Offline API
  47585. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  47586. xhr.open("GET", retryManifestURL, true);
  47587. xhr.send();
  47588. }
  47589. else {
  47590. noManifestFile();
  47591. }
  47592. }, false);
  47593. try {
  47594. xhr.send();
  47595. }
  47596. catch (ex) {
  47597. BABYLON.Tools.Error("Error on XHR send request.");
  47598. that.callbackManifestChecked(false);
  47599. }
  47600. };
  47601. Database.prototype.openAsync = function (successCallback, errorCallback) {
  47602. var _this = this;
  47603. function handleError() {
  47604. that.isSupported = false;
  47605. if (errorCallback)
  47606. errorCallback();
  47607. }
  47608. var that = this;
  47609. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  47610. // Your browser doesn't support IndexedDB
  47611. this.isSupported = false;
  47612. if (errorCallback)
  47613. errorCallback();
  47614. }
  47615. else {
  47616. // If the DB hasn't been opened or created yet
  47617. if (!this.db) {
  47618. this.hasReachedQuota = false;
  47619. this.isSupported = true;
  47620. var request = this.idbFactory.open("babylonjs", 1);
  47621. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  47622. request.onerror = function (event) {
  47623. handleError();
  47624. };
  47625. // executes when a version change transaction cannot complete due to other active transactions
  47626. request.onblocked = function (event) {
  47627. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  47628. handleError();
  47629. };
  47630. // DB has been opened successfully
  47631. request.onsuccess = function (event) {
  47632. _this.db = request.result;
  47633. successCallback();
  47634. };
  47635. // Initialization of the DB. Creating Scenes & Textures stores
  47636. request.onupgradeneeded = function (event) {
  47637. _this.db = (event.target).result;
  47638. try {
  47639. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  47640. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  47641. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  47642. }
  47643. catch (ex) {
  47644. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  47645. handleError();
  47646. }
  47647. };
  47648. }
  47649. else {
  47650. if (successCallback)
  47651. successCallback();
  47652. }
  47653. }
  47654. };
  47655. Database.prototype.loadImageFromDB = function (url, image) {
  47656. var _this = this;
  47657. var completeURL = Database.ReturnFullUrlLocation(url);
  47658. var saveAndLoadImage = function () {
  47659. if (!_this.hasReachedQuota && _this.db !== null) {
  47660. // the texture is not yet in the DB, let's try to save it
  47661. _this._saveImageIntoDBAsync(completeURL, image);
  47662. }
  47663. else {
  47664. image.src = url;
  47665. }
  47666. };
  47667. if (!this.mustUpdateRessources) {
  47668. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  47669. }
  47670. else {
  47671. saveAndLoadImage();
  47672. }
  47673. };
  47674. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  47675. if (this.isSupported && this.db !== null) {
  47676. var texture;
  47677. var transaction = this.db.transaction(["textures"]);
  47678. transaction.onabort = function (event) {
  47679. image.src = url;
  47680. };
  47681. transaction.oncomplete = function (event) {
  47682. var blobTextureURL;
  47683. if (texture) {
  47684. var URL = window.URL || window.webkitURL;
  47685. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  47686. image.onerror = function () {
  47687. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  47688. image.src = url;
  47689. };
  47690. image.src = blobTextureURL;
  47691. }
  47692. else {
  47693. notInDBCallback();
  47694. }
  47695. };
  47696. var getRequest = transaction.objectStore("textures").get(url);
  47697. getRequest.onsuccess = function (event) {
  47698. texture = (event.target).result;
  47699. };
  47700. getRequest.onerror = function (event) {
  47701. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  47702. image.src = url;
  47703. };
  47704. }
  47705. else {
  47706. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47707. image.src = url;
  47708. }
  47709. };
  47710. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  47711. var _this = this;
  47712. if (this.isSupported) {
  47713. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  47714. var generateBlobUrl = function () {
  47715. var blobTextureURL;
  47716. if (blob) {
  47717. var URL = window.URL || window.webkitURL;
  47718. try {
  47719. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  47720. }
  47721. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  47722. catch (ex) {
  47723. blobTextureURL = URL.createObjectURL(blob);
  47724. }
  47725. }
  47726. image.src = blobTextureURL;
  47727. };
  47728. if (Database.IsUASupportingBlobStorage) {
  47729. var xhr = new XMLHttpRequest(), blob;
  47730. xhr.open("GET", url, true);
  47731. xhr.responseType = "blob";
  47732. xhr.addEventListener("load", function () {
  47733. if (xhr.status === 200) {
  47734. // Blob as response (XHR2)
  47735. blob = xhr.response;
  47736. var transaction = _this.db.transaction(["textures"], "readwrite");
  47737. // the transaction could abort because of a QuotaExceededError error
  47738. transaction.onabort = function (event) {
  47739. try {
  47740. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  47741. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  47742. _this.hasReachedQuota = true;
  47743. }
  47744. }
  47745. catch (ex) { }
  47746. generateBlobUrl();
  47747. };
  47748. transaction.oncomplete = function (event) {
  47749. generateBlobUrl();
  47750. };
  47751. var newTexture = { textureUrl: url, data: blob };
  47752. try {
  47753. // Put the blob into the dabase
  47754. var addRequest = transaction.objectStore("textures").put(newTexture);
  47755. addRequest.onsuccess = function (event) {
  47756. };
  47757. addRequest.onerror = function (event) {
  47758. generateBlobUrl();
  47759. };
  47760. }
  47761. catch (ex) {
  47762. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  47763. if (ex.code === 25) {
  47764. Database.IsUASupportingBlobStorage = false;
  47765. }
  47766. image.src = url;
  47767. }
  47768. }
  47769. else {
  47770. image.src = url;
  47771. }
  47772. }, false);
  47773. xhr.addEventListener("error", function (event) {
  47774. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  47775. image.src = url;
  47776. }, false);
  47777. xhr.send();
  47778. }
  47779. else {
  47780. image.src = url;
  47781. }
  47782. }
  47783. else {
  47784. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47785. image.src = url;
  47786. }
  47787. };
  47788. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  47789. var _this = this;
  47790. var updateVersion = function (event) {
  47791. // the version is not yet in the DB or we need to update it
  47792. _this._saveVersionIntoDBAsync(url, versionLoaded);
  47793. };
  47794. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  47795. };
  47796. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  47797. var _this = this;
  47798. if (this.isSupported) {
  47799. var version;
  47800. try {
  47801. var transaction = this.db.transaction(["versions"]);
  47802. transaction.oncomplete = function (event) {
  47803. if (version) {
  47804. // If the version in the JSON file is > than the version in DB
  47805. if (_this.manifestVersionFound > version.data) {
  47806. _this.mustUpdateRessources = true;
  47807. updateInDBCallback();
  47808. }
  47809. else {
  47810. callback(version.data);
  47811. }
  47812. }
  47813. else {
  47814. _this.mustUpdateRessources = true;
  47815. updateInDBCallback();
  47816. }
  47817. };
  47818. transaction.onabort = function (event) {
  47819. callback(-1);
  47820. };
  47821. var getRequest = transaction.objectStore("versions").get(url);
  47822. getRequest.onsuccess = function (event) {
  47823. version = (event.target).result;
  47824. };
  47825. getRequest.onerror = function (event) {
  47826. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  47827. callback(-1);
  47828. };
  47829. }
  47830. catch (ex) {
  47831. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  47832. callback(-1);
  47833. }
  47834. }
  47835. else {
  47836. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47837. callback(-1);
  47838. }
  47839. };
  47840. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  47841. var _this = this;
  47842. if (this.isSupported && !this.hasReachedQuota) {
  47843. try {
  47844. // Open a transaction to the database
  47845. var transaction = this.db.transaction(["versions"], "readwrite");
  47846. // the transaction could abort because of a QuotaExceededError error
  47847. transaction.onabort = function (event) {
  47848. try {
  47849. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  47850. _this.hasReachedQuota = true;
  47851. }
  47852. }
  47853. catch (ex) { }
  47854. callback(-1);
  47855. };
  47856. transaction.oncomplete = function (event) {
  47857. callback(_this.manifestVersionFound);
  47858. };
  47859. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  47860. // Put the scene into the database
  47861. var addRequest = transaction.objectStore("versions").put(newVersion);
  47862. addRequest.onsuccess = function (event) {
  47863. };
  47864. addRequest.onerror = function (event) {
  47865. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  47866. };
  47867. }
  47868. catch (ex) {
  47869. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  47870. callback(-1);
  47871. }
  47872. }
  47873. else {
  47874. callback(-1);
  47875. }
  47876. };
  47877. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  47878. var _this = this;
  47879. var completeUrl = Database.ReturnFullUrlLocation(url);
  47880. var saveAndLoadFile = function (event) {
  47881. // the scene is not yet in the DB, let's try to save it
  47882. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  47883. };
  47884. this._checkVersionFromDB(completeUrl, function (version) {
  47885. if (version !== -1) {
  47886. if (!_this.mustUpdateRessources) {
  47887. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  47888. }
  47889. else {
  47890. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  47891. }
  47892. }
  47893. else {
  47894. errorCallback();
  47895. }
  47896. });
  47897. };
  47898. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  47899. if (this.isSupported) {
  47900. var targetStore;
  47901. if (url.indexOf(".babylon") !== -1) {
  47902. targetStore = "scenes";
  47903. }
  47904. else {
  47905. targetStore = "textures";
  47906. }
  47907. var file;
  47908. var transaction = this.db.transaction([targetStore]);
  47909. transaction.oncomplete = function (event) {
  47910. if (file) {
  47911. callback(file.data);
  47912. }
  47913. else {
  47914. notInDBCallback();
  47915. }
  47916. };
  47917. transaction.onabort = function (event) {
  47918. notInDBCallback();
  47919. };
  47920. var getRequest = transaction.objectStore(targetStore).get(url);
  47921. getRequest.onsuccess = function (event) {
  47922. file = (event.target).result;
  47923. };
  47924. getRequest.onerror = function (event) {
  47925. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  47926. notInDBCallback();
  47927. };
  47928. }
  47929. else {
  47930. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47931. callback();
  47932. }
  47933. };
  47934. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  47935. var _this = this;
  47936. if (this.isSupported) {
  47937. var targetStore;
  47938. if (url.indexOf(".babylon") !== -1) {
  47939. targetStore = "scenes";
  47940. }
  47941. else {
  47942. targetStore = "textures";
  47943. }
  47944. // Create XHR
  47945. var xhr = new XMLHttpRequest(), fileData;
  47946. xhr.open("GET", url, true);
  47947. if (useArrayBuffer) {
  47948. xhr.responseType = "arraybuffer";
  47949. }
  47950. xhr.onprogress = progressCallback;
  47951. xhr.addEventListener("load", function () {
  47952. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  47953. // Blob as response (XHR2)
  47954. //fileData = xhr.responseText;
  47955. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  47956. if (!_this.hasReachedQuota) {
  47957. // Open a transaction to the database
  47958. var transaction = _this.db.transaction([targetStore], "readwrite");
  47959. // the transaction could abort because of a QuotaExceededError error
  47960. transaction.onabort = function (event) {
  47961. try {
  47962. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  47963. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  47964. _this.hasReachedQuota = true;
  47965. }
  47966. }
  47967. catch (ex) { }
  47968. callback(fileData);
  47969. };
  47970. transaction.oncomplete = function (event) {
  47971. callback(fileData);
  47972. };
  47973. var newFile;
  47974. if (targetStore === "scenes") {
  47975. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  47976. }
  47977. else {
  47978. newFile = { textureUrl: url, data: fileData };
  47979. }
  47980. try {
  47981. // Put the scene into the database
  47982. var addRequest = transaction.objectStore(targetStore).put(newFile);
  47983. addRequest.onsuccess = function (event) {
  47984. };
  47985. addRequest.onerror = function (event) {
  47986. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  47987. };
  47988. }
  47989. catch (ex) {
  47990. callback(fileData);
  47991. }
  47992. }
  47993. else {
  47994. callback(fileData);
  47995. }
  47996. }
  47997. else {
  47998. callback();
  47999. }
  48000. }, false);
  48001. xhr.addEventListener("error", function (event) {
  48002. BABYLON.Tools.Error("error on XHR request.");
  48003. callback();
  48004. }, false);
  48005. xhr.send();
  48006. }
  48007. else {
  48008. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48009. callback();
  48010. }
  48011. };
  48012. return Database;
  48013. }());
  48014. Database.IsUASupportingBlobStorage = true;
  48015. Database.IDBStorageEnabled = true;
  48016. Database.parseURL = function (url) {
  48017. var a = document.createElement('a');
  48018. a.href = url;
  48019. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  48020. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  48021. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  48022. return absLocation;
  48023. };
  48024. Database.ReturnFullUrlLocation = function (url) {
  48025. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  48026. return (Database.parseURL(window.location.href) + url);
  48027. }
  48028. else {
  48029. return url;
  48030. }
  48031. };
  48032. BABYLON.Database = Database;
  48033. })(BABYLON || (BABYLON = {}));
  48034. //# sourceMappingURL=babylon.database.js.map
  48035. var BABYLON;
  48036. (function (BABYLON) {
  48037. var FresnelParameters = (function () {
  48038. function FresnelParameters() {
  48039. this._isEnabled = true;
  48040. this.leftColor = BABYLON.Color3.White();
  48041. this.rightColor = BABYLON.Color3.Black();
  48042. this.bias = 0;
  48043. this.power = 1;
  48044. }
  48045. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  48046. get: function () {
  48047. return this._isEnabled;
  48048. },
  48049. set: function (value) {
  48050. if (this._isEnabled === value) {
  48051. return;
  48052. }
  48053. this._isEnabled = value;
  48054. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  48055. },
  48056. enumerable: true,
  48057. configurable: true
  48058. });
  48059. FresnelParameters.prototype.clone = function () {
  48060. var newFresnelParameters = new FresnelParameters();
  48061. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  48062. return newFresnelParameters;
  48063. };
  48064. FresnelParameters.prototype.serialize = function () {
  48065. var serializationObject = {};
  48066. serializationObject.isEnabled = this.isEnabled;
  48067. serializationObject.leftColor = this.leftColor;
  48068. serializationObject.rightColor = this.rightColor;
  48069. serializationObject.bias = this.bias;
  48070. serializationObject.power = this.power;
  48071. return serializationObject;
  48072. };
  48073. FresnelParameters.Parse = function (parsedFresnelParameters) {
  48074. var fresnelParameters = new FresnelParameters();
  48075. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  48076. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  48077. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  48078. fresnelParameters.bias = parsedFresnelParameters.bias;
  48079. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  48080. return fresnelParameters;
  48081. };
  48082. return FresnelParameters;
  48083. }());
  48084. BABYLON.FresnelParameters = FresnelParameters;
  48085. })(BABYLON || (BABYLON = {}));
  48086. //# sourceMappingURL=babylon.fresnelParameters.js.map
  48087. var BABYLON;
  48088. (function (BABYLON) {
  48089. var MultiMaterial = (function (_super) {
  48090. __extends(MultiMaterial, _super);
  48091. function MultiMaterial(name, scene) {
  48092. var _this = _super.call(this, name, scene, true) || this;
  48093. scene.multiMaterials.push(_this);
  48094. _this.subMaterials = new Array();
  48095. return _this;
  48096. }
  48097. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  48098. get: function () {
  48099. return this._subMaterials;
  48100. },
  48101. set: function (value) {
  48102. this._subMaterials = value;
  48103. this._hookArray(value);
  48104. },
  48105. enumerable: true,
  48106. configurable: true
  48107. });
  48108. MultiMaterial.prototype._hookArray = function (array) {
  48109. var _this = this;
  48110. var oldPush = array.push;
  48111. array.push = function () {
  48112. var items = [];
  48113. for (var _i = 0; _i < arguments.length; _i++) {
  48114. items[_i] = arguments[_i];
  48115. }
  48116. var result = oldPush.apply(array, items);
  48117. _this._markAllSubMeshesAsTexturesDirty();
  48118. return result;
  48119. };
  48120. var oldSplice = array.splice;
  48121. array.splice = function (index, deleteCount) {
  48122. var deleted = oldSplice.apply(array, [index, deleteCount]);
  48123. _this._markAllSubMeshesAsTexturesDirty();
  48124. return deleted;
  48125. };
  48126. };
  48127. // Properties
  48128. MultiMaterial.prototype.getSubMaterial = function (index) {
  48129. if (index < 0 || index >= this.subMaterials.length) {
  48130. return this.getScene().defaultMaterial;
  48131. }
  48132. return this.subMaterials[index];
  48133. };
  48134. MultiMaterial.prototype.getActiveTextures = function () {
  48135. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  48136. var _a;
  48137. };
  48138. // Methods
  48139. MultiMaterial.prototype.getClassName = function () {
  48140. return "MultiMaterial";
  48141. };
  48142. MultiMaterial.prototype.isReady = function (mesh) {
  48143. for (var index = 0; index < this.subMaterials.length; index++) {
  48144. var subMaterial = this.subMaterials[index];
  48145. if (subMaterial) {
  48146. if (!this.subMaterials[index].isReady(mesh)) {
  48147. return false;
  48148. }
  48149. }
  48150. }
  48151. return true;
  48152. };
  48153. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  48154. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  48155. for (var index = 0; index < this.subMaterials.length; index++) {
  48156. var subMaterial = null;
  48157. if (cloneChildren) {
  48158. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  48159. }
  48160. else {
  48161. subMaterial = this.subMaterials[index];
  48162. }
  48163. newMultiMaterial.subMaterials.push(subMaterial);
  48164. }
  48165. return newMultiMaterial;
  48166. };
  48167. MultiMaterial.prototype.serialize = function () {
  48168. var serializationObject = {};
  48169. serializationObject.name = this.name;
  48170. serializationObject.id = this.id;
  48171. serializationObject.tags = BABYLON.Tags.GetTags(this);
  48172. serializationObject.materials = [];
  48173. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  48174. var subMat = this.subMaterials[matIndex];
  48175. if (subMat) {
  48176. serializationObject.materials.push(subMat.id);
  48177. }
  48178. else {
  48179. serializationObject.materials.push(null);
  48180. }
  48181. }
  48182. return serializationObject;
  48183. };
  48184. return MultiMaterial;
  48185. }(BABYLON.Material));
  48186. BABYLON.MultiMaterial = MultiMaterial;
  48187. })(BABYLON || (BABYLON = {}));
  48188. //# sourceMappingURL=babylon.multiMaterial.js.map
  48189. var BABYLON;
  48190. (function (BABYLON) {
  48191. var FreeCameraTouchInput = (function () {
  48192. function FreeCameraTouchInput() {
  48193. this._offsetX = null;
  48194. this._offsetY = null;
  48195. this._pointerCount = 0;
  48196. this._pointerPressed = [];
  48197. this.touchAngularSensibility = 200000.0;
  48198. this.touchMoveSensibility = 250.0;
  48199. }
  48200. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  48201. var _this = this;
  48202. var previousPosition;
  48203. if (this._pointerInput === undefined) {
  48204. this._onLostFocus = function (evt) {
  48205. _this._offsetX = null;
  48206. _this._offsetY = null;
  48207. };
  48208. this._pointerInput = function (p, s) {
  48209. var evt = p.event;
  48210. if (evt.pointerType === "mouse") {
  48211. return;
  48212. }
  48213. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  48214. if (!noPreventDefault) {
  48215. evt.preventDefault();
  48216. }
  48217. _this._pointerPressed.push(evt.pointerId);
  48218. if (_this._pointerPressed.length !== 1) {
  48219. return;
  48220. }
  48221. previousPosition = {
  48222. x: evt.clientX,
  48223. y: evt.clientY
  48224. };
  48225. }
  48226. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  48227. if (!noPreventDefault) {
  48228. evt.preventDefault();
  48229. }
  48230. var index = _this._pointerPressed.indexOf(evt.pointerId);
  48231. if (index === -1) {
  48232. return;
  48233. }
  48234. _this._pointerPressed.splice(index, 1);
  48235. if (index != 0) {
  48236. return;
  48237. }
  48238. previousPosition = null;
  48239. _this._offsetX = null;
  48240. _this._offsetY = null;
  48241. }
  48242. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48243. if (!noPreventDefault) {
  48244. evt.preventDefault();
  48245. }
  48246. if (!previousPosition) {
  48247. return;
  48248. }
  48249. var index = _this._pointerPressed.indexOf(evt.pointerId);
  48250. if (index != 0) {
  48251. return;
  48252. }
  48253. _this._offsetX = evt.clientX - previousPosition.x;
  48254. _this._offsetY = -(evt.clientY - previousPosition.y);
  48255. }
  48256. };
  48257. }
  48258. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48259. element.addEventListener("blur", this._onLostFocus);
  48260. };
  48261. FreeCameraTouchInput.prototype.detachControl = function (element) {
  48262. if (this._pointerInput && element) {
  48263. this.camera.getScene().onPointerObservable.remove(this._observer);
  48264. this._observer = null;
  48265. element.removeEventListener("blur", this._onLostFocus);
  48266. this._onLostFocus = null;
  48267. this._pointerPressed = [];
  48268. this._offsetX = null;
  48269. this._offsetY = null;
  48270. this._pointerCount = 0;
  48271. }
  48272. };
  48273. FreeCameraTouchInput.prototype.checkInputs = function () {
  48274. if (this._offsetX) {
  48275. var camera = this.camera;
  48276. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  48277. if (this._pointerPressed.length > 1) {
  48278. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  48279. }
  48280. else {
  48281. var speed = camera._computeLocalCameraSpeed();
  48282. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  48283. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  48284. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  48285. }
  48286. }
  48287. };
  48288. FreeCameraTouchInput.prototype.getTypeName = function () {
  48289. return "FreeCameraTouchInput";
  48290. };
  48291. FreeCameraTouchInput.prototype.getSimpleName = function () {
  48292. return "touch";
  48293. };
  48294. return FreeCameraTouchInput;
  48295. }());
  48296. __decorate([
  48297. BABYLON.serialize()
  48298. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  48299. __decorate([
  48300. BABYLON.serialize()
  48301. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  48302. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  48303. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  48304. })(BABYLON || (BABYLON = {}));
  48305. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  48306. /// <reference path="babylon.freeCamera.ts" />
  48307. var BABYLON;
  48308. (function (BABYLON) {
  48309. // We're mainly based on the logic defined into the FreeCamera code
  48310. var TouchCamera = (function (_super) {
  48311. __extends(TouchCamera, _super);
  48312. //-- end properties for backward compatibility for inputs
  48313. function TouchCamera(name, position, scene) {
  48314. var _this = _super.call(this, name, position, scene) || this;
  48315. _this.inputs.addTouch();
  48316. _this._setupInputs();
  48317. return _this;
  48318. }
  48319. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  48320. //-- Begin properties for backward compatibility for inputs
  48321. get: function () {
  48322. var touch = this.inputs.attached["touch"];
  48323. if (touch)
  48324. return touch.touchAngularSensibility;
  48325. },
  48326. set: function (value) {
  48327. var touch = this.inputs.attached["touch"];
  48328. if (touch)
  48329. touch.touchAngularSensibility = value;
  48330. },
  48331. enumerable: true,
  48332. configurable: true
  48333. });
  48334. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  48335. get: function () {
  48336. var touch = this.inputs.attached["touch"];
  48337. if (touch)
  48338. return touch.touchMoveSensibility;
  48339. },
  48340. set: function (value) {
  48341. var touch = this.inputs.attached["touch"];
  48342. if (touch)
  48343. touch.touchMoveSensibility = value;
  48344. },
  48345. enumerable: true,
  48346. configurable: true
  48347. });
  48348. TouchCamera.prototype.getClassName = function () {
  48349. return "TouchCamera";
  48350. };
  48351. TouchCamera.prototype._setupInputs = function () {
  48352. var mouse = this.inputs.attached["mouse"];
  48353. if (mouse) {
  48354. mouse.touchEnabled = false;
  48355. }
  48356. };
  48357. return TouchCamera;
  48358. }(BABYLON.FreeCamera));
  48359. BABYLON.TouchCamera = TouchCamera;
  48360. })(BABYLON || (BABYLON = {}));
  48361. //# sourceMappingURL=babylon.touchCamera.js.map
  48362. var BABYLON;
  48363. (function (BABYLON) {
  48364. var ProceduralTexture = (function (_super) {
  48365. __extends(ProceduralTexture, _super);
  48366. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  48367. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48368. if (isCube === void 0) { isCube = false; }
  48369. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  48370. _this.isCube = isCube;
  48371. _this.isEnabled = true;
  48372. _this._currentRefreshId = -1;
  48373. _this._refreshRate = 1;
  48374. _this._vertexBuffers = {};
  48375. _this._uniforms = new Array();
  48376. _this._samplers = new Array();
  48377. _this._textures = new Array();
  48378. _this._floats = new Array();
  48379. _this._floatsArrays = {};
  48380. _this._colors3 = new Array();
  48381. _this._colors4 = new Array();
  48382. _this._vectors2 = new Array();
  48383. _this._vectors3 = new Array();
  48384. _this._matrices = new Array();
  48385. _this._fallbackTextureUsed = false;
  48386. scene._proceduralTextures.push(_this);
  48387. _this.name = name;
  48388. _this.isRenderTarget = true;
  48389. _this._size = size;
  48390. _this._generateMipMaps = generateMipMaps;
  48391. _this.setFragment(fragment);
  48392. _this._fallbackTexture = fallbackTexture;
  48393. var engine = scene.getEngine();
  48394. if (isCube) {
  48395. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  48396. _this.setFloat("face", 0);
  48397. }
  48398. else {
  48399. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  48400. }
  48401. // VBO
  48402. var vertices = [];
  48403. vertices.push(1, 1);
  48404. vertices.push(-1, 1);
  48405. vertices.push(-1, -1);
  48406. vertices.push(1, -1);
  48407. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  48408. // Indices
  48409. var indices = [];
  48410. indices.push(0);
  48411. indices.push(1);
  48412. indices.push(2);
  48413. indices.push(0);
  48414. indices.push(2);
  48415. indices.push(3);
  48416. _this._indexBuffer = engine.createIndexBuffer(indices);
  48417. return _this;
  48418. }
  48419. ProceduralTexture.prototype.reset = function () {
  48420. if (this._effect === undefined) {
  48421. return;
  48422. }
  48423. var engine = this.getScene().getEngine();
  48424. engine._releaseEffect(this._effect);
  48425. };
  48426. ProceduralTexture.prototype.isReady = function () {
  48427. var _this = this;
  48428. var engine = this.getScene().getEngine();
  48429. var shaders;
  48430. if (!this._fragment) {
  48431. return false;
  48432. }
  48433. if (this._fallbackTextureUsed) {
  48434. return true;
  48435. }
  48436. if (this._fragment.fragmentElement !== undefined) {
  48437. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  48438. }
  48439. else {
  48440. shaders = { vertex: "procedural", fragment: this._fragment };
  48441. }
  48442. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  48443. _this.releaseInternalTexture();
  48444. if (_this._fallbackTexture) {
  48445. _this._texture = _this._fallbackTexture._texture;
  48446. _this._texture.references++;
  48447. }
  48448. _this._fallbackTextureUsed = true;
  48449. });
  48450. return this._effect.isReady();
  48451. };
  48452. ProceduralTexture.prototype.resetRefreshCounter = function () {
  48453. this._currentRefreshId = -1;
  48454. };
  48455. ProceduralTexture.prototype.setFragment = function (fragment) {
  48456. this._fragment = fragment;
  48457. };
  48458. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  48459. get: function () {
  48460. return this._refreshRate;
  48461. },
  48462. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  48463. set: function (value) {
  48464. this._refreshRate = value;
  48465. this.resetRefreshCounter();
  48466. },
  48467. enumerable: true,
  48468. configurable: true
  48469. });
  48470. ProceduralTexture.prototype._shouldRender = function () {
  48471. if (!this.isEnabled || !this.isReady() || !this._texture) {
  48472. return false;
  48473. }
  48474. if (this._fallbackTextureUsed) {
  48475. return false;
  48476. }
  48477. if (this._currentRefreshId === -1) {
  48478. this._currentRefreshId = 1;
  48479. return true;
  48480. }
  48481. if (this.refreshRate === this._currentRefreshId) {
  48482. this._currentRefreshId = 1;
  48483. return true;
  48484. }
  48485. this._currentRefreshId++;
  48486. return false;
  48487. };
  48488. ProceduralTexture.prototype.getRenderSize = function () {
  48489. return this._size;
  48490. };
  48491. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  48492. if (this._fallbackTextureUsed) {
  48493. return;
  48494. }
  48495. this.releaseInternalTexture();
  48496. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  48497. };
  48498. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  48499. if (this._uniforms.indexOf(uniformName) === -1) {
  48500. this._uniforms.push(uniformName);
  48501. }
  48502. };
  48503. ProceduralTexture.prototype.setTexture = function (name, texture) {
  48504. if (this._samplers.indexOf(name) === -1) {
  48505. this._samplers.push(name);
  48506. }
  48507. this._textures[name] = texture;
  48508. return this;
  48509. };
  48510. ProceduralTexture.prototype.setFloat = function (name, value) {
  48511. this._checkUniform(name);
  48512. this._floats[name] = value;
  48513. return this;
  48514. };
  48515. ProceduralTexture.prototype.setFloats = function (name, value) {
  48516. this._checkUniform(name);
  48517. this._floatsArrays[name] = value;
  48518. return this;
  48519. };
  48520. ProceduralTexture.prototype.setColor3 = function (name, value) {
  48521. this._checkUniform(name);
  48522. this._colors3[name] = value;
  48523. return this;
  48524. };
  48525. ProceduralTexture.prototype.setColor4 = function (name, value) {
  48526. this._checkUniform(name);
  48527. this._colors4[name] = value;
  48528. return this;
  48529. };
  48530. ProceduralTexture.prototype.setVector2 = function (name, value) {
  48531. this._checkUniform(name);
  48532. this._vectors2[name] = value;
  48533. return this;
  48534. };
  48535. ProceduralTexture.prototype.setVector3 = function (name, value) {
  48536. this._checkUniform(name);
  48537. this._vectors3[name] = value;
  48538. return this;
  48539. };
  48540. ProceduralTexture.prototype.setMatrix = function (name, value) {
  48541. this._checkUniform(name);
  48542. this._matrices[name] = value;
  48543. return this;
  48544. };
  48545. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  48546. var scene = this.getScene();
  48547. var engine = scene.getEngine();
  48548. // Render
  48549. engine.enableEffect(this._effect);
  48550. engine.setState(false);
  48551. // Texture
  48552. for (var name in this._textures) {
  48553. this._effect.setTexture(name, this._textures[name]);
  48554. }
  48555. // Float
  48556. for (name in this._floats) {
  48557. this._effect.setFloat(name, this._floats[name]);
  48558. }
  48559. // Floats
  48560. for (name in this._floatsArrays) {
  48561. this._effect.setArray(name, this._floatsArrays[name]);
  48562. }
  48563. // Color3
  48564. for (name in this._colors3) {
  48565. this._effect.setColor3(name, this._colors3[name]);
  48566. }
  48567. // Color4
  48568. for (name in this._colors4) {
  48569. var color = this._colors4[name];
  48570. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48571. }
  48572. // Vector2
  48573. for (name in this._vectors2) {
  48574. this._effect.setVector2(name, this._vectors2[name]);
  48575. }
  48576. // Vector3
  48577. for (name in this._vectors3) {
  48578. this._effect.setVector3(name, this._vectors3[name]);
  48579. }
  48580. // Matrix
  48581. for (name in this._matrices) {
  48582. this._effect.setMatrix(name, this._matrices[name]);
  48583. }
  48584. if (this.isCube) {
  48585. for (var face = 0; face < 6; face++) {
  48586. engine.bindFramebuffer(this._texture, face);
  48587. // VBOs
  48588. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  48589. this._effect.setFloat("face", face);
  48590. // Clear
  48591. engine.clear(scene.clearColor, true, true, true);
  48592. // Draw order
  48593. engine.draw(true, 0, 6);
  48594. // Mipmaps
  48595. if (face === 5) {
  48596. engine.generateMipMapsForCubemap(this._texture);
  48597. }
  48598. }
  48599. }
  48600. else {
  48601. engine.bindFramebuffer(this._texture);
  48602. // VBOs
  48603. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  48604. // Clear
  48605. engine.clear(scene.clearColor, true, true, true);
  48606. // Draw order
  48607. engine.draw(true, 0, 6);
  48608. }
  48609. // Unbind
  48610. engine.unBindFramebuffer(this._texture, this.isCube);
  48611. if (this.onGenerated) {
  48612. this.onGenerated();
  48613. }
  48614. };
  48615. ProceduralTexture.prototype.clone = function () {
  48616. var textureSize = this.getSize();
  48617. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  48618. // Base texture
  48619. newTexture.hasAlpha = this.hasAlpha;
  48620. newTexture.level = this.level;
  48621. // RenderTarget Texture
  48622. newTexture.coordinatesMode = this.coordinatesMode;
  48623. return newTexture;
  48624. };
  48625. ProceduralTexture.prototype.dispose = function () {
  48626. var index = this.getScene()._proceduralTextures.indexOf(this);
  48627. if (index >= 0) {
  48628. this.getScene()._proceduralTextures.splice(index, 1);
  48629. }
  48630. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  48631. if (vertexBuffer) {
  48632. vertexBuffer.dispose();
  48633. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  48634. }
  48635. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  48636. this._indexBuffer = null;
  48637. }
  48638. _super.prototype.dispose.call(this);
  48639. };
  48640. return ProceduralTexture;
  48641. }(BABYLON.Texture));
  48642. BABYLON.ProceduralTexture = ProceduralTexture;
  48643. })(BABYLON || (BABYLON = {}));
  48644. //# sourceMappingURL=babylon.proceduralTexture.js.map
  48645. /// <reference path="babylon.proceduralTexture.ts" />
  48646. var BABYLON;
  48647. (function (BABYLON) {
  48648. var CustomProceduralTexture = (function (_super) {
  48649. __extends(CustomProceduralTexture, _super);
  48650. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  48651. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  48652. _this._animate = true;
  48653. _this._time = 0;
  48654. _this._texturePath = texturePath;
  48655. //Try to load json
  48656. _this.loadJson(texturePath);
  48657. _this.refreshRate = 1;
  48658. return _this;
  48659. }
  48660. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  48661. var _this = this;
  48662. var that = this;
  48663. function noConfigFile() {
  48664. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  48665. try {
  48666. that.setFragment(that._texturePath);
  48667. }
  48668. catch (ex) {
  48669. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  48670. }
  48671. }
  48672. var configFileUrl = jsonUrl + "/config.json";
  48673. var xhr = new XMLHttpRequest();
  48674. xhr.open("GET", configFileUrl, true);
  48675. xhr.addEventListener("load", function () {
  48676. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  48677. try {
  48678. _this._config = JSON.parse(xhr.response);
  48679. _this.updateShaderUniforms();
  48680. _this.updateTextures();
  48681. _this.setFragment(_this._texturePath + "/custom");
  48682. _this._animate = _this._config.animate;
  48683. _this.refreshRate = _this._config.refreshrate;
  48684. }
  48685. catch (ex) {
  48686. noConfigFile();
  48687. }
  48688. }
  48689. else {
  48690. noConfigFile();
  48691. }
  48692. }, false);
  48693. xhr.addEventListener("error", function () {
  48694. noConfigFile();
  48695. }, false);
  48696. try {
  48697. xhr.send();
  48698. }
  48699. catch (ex) {
  48700. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  48701. }
  48702. };
  48703. CustomProceduralTexture.prototype.isReady = function () {
  48704. if (!_super.prototype.isReady.call(this)) {
  48705. return false;
  48706. }
  48707. for (var name in this._textures) {
  48708. var texture = this._textures[name];
  48709. if (!texture.isReady()) {
  48710. return false;
  48711. }
  48712. }
  48713. return true;
  48714. };
  48715. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  48716. if (this._animate) {
  48717. this._time += this.getScene().getAnimationRatio() * 0.03;
  48718. this.updateShaderUniforms();
  48719. }
  48720. _super.prototype.render.call(this, useCameraPostProcess);
  48721. };
  48722. CustomProceduralTexture.prototype.updateTextures = function () {
  48723. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  48724. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  48725. }
  48726. };
  48727. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  48728. if (this._config) {
  48729. for (var j = 0; j < this._config.uniforms.length; j++) {
  48730. var uniform = this._config.uniforms[j];
  48731. switch (uniform.type) {
  48732. case "float":
  48733. this.setFloat(uniform.name, uniform.value);
  48734. break;
  48735. case "color3":
  48736. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  48737. break;
  48738. case "color4":
  48739. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  48740. break;
  48741. case "vector2":
  48742. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  48743. break;
  48744. case "vector3":
  48745. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  48746. break;
  48747. }
  48748. }
  48749. }
  48750. this.setFloat("time", this._time);
  48751. };
  48752. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  48753. get: function () {
  48754. return this._animate;
  48755. },
  48756. set: function (value) {
  48757. this._animate = value;
  48758. },
  48759. enumerable: true,
  48760. configurable: true
  48761. });
  48762. return CustomProceduralTexture;
  48763. }(BABYLON.ProceduralTexture));
  48764. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  48765. })(BABYLON || (BABYLON = {}));
  48766. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  48767. var BABYLON;
  48768. (function (BABYLON) {
  48769. var FreeCameraGamepadInput = (function () {
  48770. function FreeCameraGamepadInput() {
  48771. this.gamepadAngularSensibility = 200;
  48772. this.gamepadMoveSensibility = 40;
  48773. // private members
  48774. this._cameraTransform = BABYLON.Matrix.Identity();
  48775. this._deltaTransform = BABYLON.Vector3.Zero();
  48776. this._vector3 = BABYLON.Vector3.Zero();
  48777. this._vector2 = BABYLON.Vector2.Zero();
  48778. }
  48779. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  48780. var _this = this;
  48781. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  48782. };
  48783. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  48784. if (this._gamepads) {
  48785. this._gamepads.dispose();
  48786. }
  48787. this.gamepad = null;
  48788. };
  48789. FreeCameraGamepadInput.prototype.checkInputs = function () {
  48790. if (this.gamepad && this.gamepad.leftStick) {
  48791. var camera = this.camera;
  48792. var LSValues = this.gamepad.leftStick;
  48793. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  48794. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  48795. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  48796. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  48797. var RSValues = this.gamepad.rightStick;
  48798. if (RSValues) {
  48799. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  48800. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  48801. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  48802. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  48803. }
  48804. else {
  48805. RSValues = { x: 0, y: 0 };
  48806. }
  48807. if (!camera.rotationQuaternion) {
  48808. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  48809. }
  48810. else {
  48811. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  48812. }
  48813. var speed = camera._computeLocalCameraSpeed() * 50.0;
  48814. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  48815. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  48816. camera.cameraDirection.addInPlace(this._deltaTransform);
  48817. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  48818. camera.cameraRotation.addInPlace(this._vector2);
  48819. }
  48820. };
  48821. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  48822. // Only the first gamepad found can control the camera
  48823. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  48824. // prioritize XBOX gamepads.
  48825. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  48826. this.gamepad = gamepad;
  48827. }
  48828. }
  48829. };
  48830. FreeCameraGamepadInput.prototype.getTypeName = function () {
  48831. return "FreeCameraGamepadInput";
  48832. };
  48833. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  48834. return "gamepad";
  48835. };
  48836. return FreeCameraGamepadInput;
  48837. }());
  48838. __decorate([
  48839. BABYLON.serialize()
  48840. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  48841. __decorate([
  48842. BABYLON.serialize()
  48843. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  48844. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  48845. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  48846. })(BABYLON || (BABYLON = {}));
  48847. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  48848. var BABYLON;
  48849. (function (BABYLON) {
  48850. var ArcRotateCameraGamepadInput = (function () {
  48851. function ArcRotateCameraGamepadInput() {
  48852. this.gamepadRotationSensibility = 80;
  48853. this.gamepadMoveSensibility = 40;
  48854. }
  48855. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  48856. var _this = this;
  48857. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  48858. };
  48859. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  48860. if (this._gamepads) {
  48861. this._gamepads.dispose();
  48862. }
  48863. this.gamepad = null;
  48864. };
  48865. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  48866. if (this.gamepad) {
  48867. var camera = this.camera;
  48868. var RSValues = this.gamepad.rightStick;
  48869. if (RSValues) {
  48870. if (RSValues.x != 0) {
  48871. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  48872. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  48873. camera.inertialAlphaOffset += normalizedRX;
  48874. }
  48875. }
  48876. if (RSValues.y != 0) {
  48877. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  48878. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  48879. camera.inertialBetaOffset += normalizedRY;
  48880. }
  48881. }
  48882. }
  48883. var LSValues = this.gamepad.leftStick;
  48884. if (LSValues && LSValues.y != 0) {
  48885. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  48886. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  48887. this.camera.inertialRadiusOffset -= normalizedLY;
  48888. }
  48889. }
  48890. }
  48891. };
  48892. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  48893. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  48894. // prioritize XBOX gamepads.
  48895. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  48896. this.gamepad = gamepad;
  48897. }
  48898. }
  48899. };
  48900. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  48901. return "ArcRotateCameraGamepadInput";
  48902. };
  48903. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  48904. return "gamepad";
  48905. };
  48906. return ArcRotateCameraGamepadInput;
  48907. }());
  48908. __decorate([
  48909. BABYLON.serialize()
  48910. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  48911. __decorate([
  48912. BABYLON.serialize()
  48913. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  48914. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  48915. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  48916. })(BABYLON || (BABYLON = {}));
  48917. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  48918. var BABYLON;
  48919. (function (BABYLON) {
  48920. var Gamepads = (function () {
  48921. function Gamepads(ongamedpadconnected, ongamedpaddisconnected) {
  48922. var _this = this;
  48923. this.babylonGamepads = [];
  48924. this.oneGamepadConnected = false;
  48925. this.isMonitoring = false;
  48926. this.gamepadEventSupported = 'GamepadEvent' in window;
  48927. this.gamepadSupport = (navigator.getGamepads ||
  48928. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  48929. this._callbackGamepadConnected = ongamedpadconnected;
  48930. this._callbackGamepadDisconnected = ongamedpaddisconnected;
  48931. if (this.gamepadSupport) {
  48932. //first add already-connected gamepads
  48933. this._updateGamepadObjects();
  48934. if (this.babylonGamepads.length) {
  48935. this._startMonitoringGamepads();
  48936. }
  48937. // Checking if the gamepad connected event is supported (like in Firefox)
  48938. if (this.gamepadEventSupported) {
  48939. this._onGamepadConnectedEvent = function (evt) {
  48940. _this._onGamepadConnected(evt.gamepad);
  48941. };
  48942. this._onGamepadDisonnectedEvent = function (evt) {
  48943. _this._onGamepadDisconnected(evt.gamepad);
  48944. };
  48945. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  48946. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  48947. }
  48948. else {
  48949. this._startMonitoringGamepads();
  48950. }
  48951. }
  48952. }
  48953. Gamepads.prototype.dispose = function () {
  48954. if (this._onGamepadConnectedEvent) {
  48955. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  48956. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  48957. this._onGamepadConnectedEvent = null;
  48958. this._onGamepadDisonnectedEvent = null;
  48959. }
  48960. this.oneGamepadConnected = false;
  48961. this._stopMonitoringGamepads();
  48962. this.babylonGamepads = [];
  48963. };
  48964. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  48965. // Protection code for Chrome which has a very buggy gamepad implementation...
  48966. // And raises a connected event on disconnection for instance
  48967. if (gamepad.index in this.babylonGamepads) {
  48968. return;
  48969. }
  48970. var newGamepad = this._addNewGamepad(gamepad);
  48971. if (this._callbackGamepadConnected)
  48972. this._callbackGamepadConnected(newGamepad);
  48973. this._startMonitoringGamepads();
  48974. };
  48975. Gamepads.prototype._addNewGamepad = function (gamepad) {
  48976. if (!this.oneGamepadConnected) {
  48977. this.oneGamepadConnected = true;
  48978. }
  48979. var newGamepad;
  48980. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  48981. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  48982. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  48983. }
  48984. else if (gamepad.pose) {
  48985. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  48986. }
  48987. else {
  48988. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  48989. }
  48990. this.babylonGamepads.push(newGamepad);
  48991. return newGamepad;
  48992. };
  48993. Gamepads.prototype._onGamepadDisconnected = function (gamepad) {
  48994. // Remove the gamepad from the list of gamepads to monitor.
  48995. for (var i in this.babylonGamepads) {
  48996. if (this.babylonGamepads[i].index == gamepad.index) {
  48997. this.babylonGamepads.splice(+i, 1);
  48998. break;
  48999. }
  49000. }
  49001. // If no gamepads are left, stop the polling loop.
  49002. if (this.babylonGamepads.length == 0) {
  49003. this._stopMonitoringGamepads();
  49004. this.oneGamepadConnected = false;
  49005. }
  49006. if (this._callbackGamepadDisconnected)
  49007. this._callbackGamepadDisconnected(gamepad);
  49008. };
  49009. Gamepads.prototype._startMonitoringGamepads = function () {
  49010. if (!this.isMonitoring) {
  49011. this.isMonitoring = true;
  49012. this._checkGamepadsStatus();
  49013. }
  49014. };
  49015. Gamepads.prototype._stopMonitoringGamepads = function () {
  49016. this.isMonitoring = false;
  49017. };
  49018. Gamepads.prototype._checkGamepadsStatus = function () {
  49019. var _this = this;
  49020. // Hack to be compatible Chrome
  49021. this._updateGamepadObjects();
  49022. for (var i in this.babylonGamepads) {
  49023. this.babylonGamepads[i].update();
  49024. }
  49025. if (this.isMonitoring) {
  49026. if (window.requestAnimationFrame) {
  49027. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49028. }
  49029. else if (window.mozRequestAnimationFrame) {
  49030. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49031. }
  49032. else if (window.webkitRequestAnimationFrame) {
  49033. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49034. }
  49035. }
  49036. };
  49037. // This function is called only on Chrome, which does not properly support
  49038. // connection/disconnection events and forces you to recopy again the gamepad object
  49039. Gamepads.prototype._updateGamepadObjects = function () {
  49040. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  49041. for (var i = 0; i < gamepads.length; i++) {
  49042. if (gamepads[i]) {
  49043. if (!(gamepads[i].index in this.babylonGamepads)) {
  49044. var newGamepad = this._addNewGamepad(gamepads[i]);
  49045. if (this._callbackGamepadConnected) {
  49046. this._callbackGamepadConnected(newGamepad);
  49047. }
  49048. }
  49049. else {
  49050. // Forced to copy again this object for Chrome for unknown reason
  49051. this.babylonGamepads[i].browserGamepad = gamepads[i];
  49052. }
  49053. }
  49054. }
  49055. };
  49056. return Gamepads;
  49057. }());
  49058. BABYLON.Gamepads = Gamepads;
  49059. var StickValues = (function () {
  49060. function StickValues(x, y) {
  49061. this.x = x;
  49062. this.y = y;
  49063. }
  49064. return StickValues;
  49065. }());
  49066. BABYLON.StickValues = StickValues;
  49067. var Gamepad = (function () {
  49068. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  49069. if (leftStickX === void 0) { leftStickX = 0; }
  49070. if (leftStickY === void 0) { leftStickY = 1; }
  49071. if (rightStickX === void 0) { rightStickX = 2; }
  49072. if (rightStickY === void 0) { rightStickY = 3; }
  49073. this.id = id;
  49074. this.index = index;
  49075. this.browserGamepad = browserGamepad;
  49076. this.type = Gamepad.GAMEPAD;
  49077. this._leftStickAxisX = leftStickX;
  49078. this._leftStickAxisY = leftStickY;
  49079. this._rightStickAxisX = rightStickX;
  49080. this._rightStickAxisY = rightStickY;
  49081. if (this.browserGamepad.axes.length >= 2) {
  49082. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49083. }
  49084. if (this.browserGamepad.axes.length >= 4) {
  49085. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49086. }
  49087. }
  49088. Gamepad.prototype.onleftstickchanged = function (callback) {
  49089. this._onleftstickchanged = callback;
  49090. };
  49091. Gamepad.prototype.onrightstickchanged = function (callback) {
  49092. this._onrightstickchanged = callback;
  49093. };
  49094. Object.defineProperty(Gamepad.prototype, "leftStick", {
  49095. get: function () {
  49096. return this._leftStick;
  49097. },
  49098. set: function (newValues) {
  49099. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  49100. this._onleftstickchanged(newValues);
  49101. }
  49102. this._leftStick = newValues;
  49103. },
  49104. enumerable: true,
  49105. configurable: true
  49106. });
  49107. Object.defineProperty(Gamepad.prototype, "rightStick", {
  49108. get: function () {
  49109. return this._rightStick;
  49110. },
  49111. set: function (newValues) {
  49112. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  49113. this._onrightstickchanged(newValues);
  49114. }
  49115. this._rightStick = newValues;
  49116. },
  49117. enumerable: true,
  49118. configurable: true
  49119. });
  49120. Gamepad.prototype.update = function () {
  49121. if (this._leftStick) {
  49122. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49123. }
  49124. if (this._rightStick) {
  49125. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49126. }
  49127. };
  49128. return Gamepad;
  49129. }());
  49130. Gamepad.GAMEPAD = 0;
  49131. Gamepad.GENERIC = 1;
  49132. Gamepad.XBOX = 2;
  49133. Gamepad.POSE_ENABLED = 3;
  49134. BABYLON.Gamepad = Gamepad;
  49135. var GenericPad = (function (_super) {
  49136. __extends(GenericPad, _super);
  49137. function GenericPad(id, index, browserGamepad) {
  49138. var _this = _super.call(this, id, index, browserGamepad) || this;
  49139. _this.type = Gamepad.GENERIC;
  49140. _this._buttons = new Array(browserGamepad.buttons.length);
  49141. return _this;
  49142. }
  49143. GenericPad.prototype.onbuttondown = function (callback) {
  49144. this._onbuttondown = callback;
  49145. };
  49146. GenericPad.prototype.onbuttonup = function (callback) {
  49147. this._onbuttonup = callback;
  49148. };
  49149. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  49150. if (newValue !== currentValue) {
  49151. if (this._onbuttondown && newValue === 1) {
  49152. this._onbuttondown(buttonIndex);
  49153. }
  49154. if (this._onbuttonup && newValue === 0) {
  49155. this._onbuttonup(buttonIndex);
  49156. }
  49157. }
  49158. return newValue;
  49159. };
  49160. GenericPad.prototype.update = function () {
  49161. _super.prototype.update.call(this);
  49162. for (var index = 0; index < this._buttons.length; index++) {
  49163. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  49164. }
  49165. };
  49166. return GenericPad;
  49167. }(Gamepad));
  49168. BABYLON.GenericPad = GenericPad;
  49169. var Xbox360Button;
  49170. (function (Xbox360Button) {
  49171. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  49172. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  49173. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  49174. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  49175. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  49176. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  49177. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  49178. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  49179. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  49180. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  49181. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  49182. var Xbox360Dpad;
  49183. (function (Xbox360Dpad) {
  49184. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  49185. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  49186. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  49187. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  49188. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  49189. var Xbox360Pad = (function (_super) {
  49190. __extends(Xbox360Pad, _super);
  49191. function Xbox360Pad(id, index, gamepad, xboxOne) {
  49192. if (xboxOne === void 0) { xboxOne = false; }
  49193. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  49194. _this._leftTrigger = 0;
  49195. _this._rightTrigger = 0;
  49196. _this._buttonA = 0;
  49197. _this._buttonB = 0;
  49198. _this._buttonX = 0;
  49199. _this._buttonY = 0;
  49200. _this._buttonBack = 0;
  49201. _this._buttonStart = 0;
  49202. _this._buttonLB = 0;
  49203. _this._buttonRB = 0;
  49204. _this._buttonLeftStick = 0;
  49205. _this._buttonRightStick = 0;
  49206. _this._dPadUp = 0;
  49207. _this._dPadDown = 0;
  49208. _this._dPadLeft = 0;
  49209. _this._dPadRight = 0;
  49210. _this._isXboxOnePad = false;
  49211. _this.type = Gamepad.XBOX;
  49212. _this._isXboxOnePad = xboxOne;
  49213. return _this;
  49214. }
  49215. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  49216. this._onlefttriggerchanged = callback;
  49217. };
  49218. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  49219. this._onrighttriggerchanged = callback;
  49220. };
  49221. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  49222. get: function () {
  49223. return this._leftTrigger;
  49224. },
  49225. set: function (newValue) {
  49226. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  49227. this._onlefttriggerchanged(newValue);
  49228. }
  49229. this._leftTrigger = newValue;
  49230. },
  49231. enumerable: true,
  49232. configurable: true
  49233. });
  49234. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  49235. get: function () {
  49236. return this._rightTrigger;
  49237. },
  49238. set: function (newValue) {
  49239. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  49240. this._onrighttriggerchanged(newValue);
  49241. }
  49242. this._rightTrigger = newValue;
  49243. },
  49244. enumerable: true,
  49245. configurable: true
  49246. });
  49247. Xbox360Pad.prototype.onbuttondown = function (callback) {
  49248. this._onbuttondown = callback;
  49249. };
  49250. Xbox360Pad.prototype.onbuttonup = function (callback) {
  49251. this._onbuttonup = callback;
  49252. };
  49253. Xbox360Pad.prototype.ondpaddown = function (callback) {
  49254. this._ondpaddown = callback;
  49255. };
  49256. Xbox360Pad.prototype.ondpadup = function (callback) {
  49257. this._ondpadup = callback;
  49258. };
  49259. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  49260. if (newValue !== currentValue) {
  49261. if (this._onbuttondown && newValue === 1) {
  49262. this._onbuttondown(buttonType);
  49263. }
  49264. if (this._onbuttonup && newValue === 0) {
  49265. this._onbuttonup(buttonType);
  49266. }
  49267. }
  49268. return newValue;
  49269. };
  49270. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  49271. if (newValue !== currentValue) {
  49272. if (this._ondpaddown && newValue === 1) {
  49273. this._ondpaddown(buttonType);
  49274. }
  49275. if (this._ondpadup && newValue === 0) {
  49276. this._ondpadup(buttonType);
  49277. }
  49278. }
  49279. return newValue;
  49280. };
  49281. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  49282. get: function () {
  49283. return this._buttonA;
  49284. },
  49285. set: function (value) {
  49286. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  49287. },
  49288. enumerable: true,
  49289. configurable: true
  49290. });
  49291. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  49292. get: function () {
  49293. return this._buttonB;
  49294. },
  49295. set: function (value) {
  49296. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  49297. },
  49298. enumerable: true,
  49299. configurable: true
  49300. });
  49301. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  49302. get: function () {
  49303. return this._buttonX;
  49304. },
  49305. set: function (value) {
  49306. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  49307. },
  49308. enumerable: true,
  49309. configurable: true
  49310. });
  49311. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  49312. get: function () {
  49313. return this._buttonY;
  49314. },
  49315. set: function (value) {
  49316. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  49317. },
  49318. enumerable: true,
  49319. configurable: true
  49320. });
  49321. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  49322. get: function () {
  49323. return this._buttonStart;
  49324. },
  49325. set: function (value) {
  49326. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  49327. },
  49328. enumerable: true,
  49329. configurable: true
  49330. });
  49331. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  49332. get: function () {
  49333. return this._buttonBack;
  49334. },
  49335. set: function (value) {
  49336. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  49337. },
  49338. enumerable: true,
  49339. configurable: true
  49340. });
  49341. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  49342. get: function () {
  49343. return this._buttonLB;
  49344. },
  49345. set: function (value) {
  49346. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  49347. },
  49348. enumerable: true,
  49349. configurable: true
  49350. });
  49351. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  49352. get: function () {
  49353. return this._buttonRB;
  49354. },
  49355. set: function (value) {
  49356. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  49357. },
  49358. enumerable: true,
  49359. configurable: true
  49360. });
  49361. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  49362. get: function () {
  49363. return this._buttonLeftStick;
  49364. },
  49365. set: function (value) {
  49366. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  49367. },
  49368. enumerable: true,
  49369. configurable: true
  49370. });
  49371. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  49372. get: function () {
  49373. return this._buttonRightStick;
  49374. },
  49375. set: function (value) {
  49376. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  49377. },
  49378. enumerable: true,
  49379. configurable: true
  49380. });
  49381. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  49382. get: function () {
  49383. return this._dPadUp;
  49384. },
  49385. set: function (value) {
  49386. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  49387. },
  49388. enumerable: true,
  49389. configurable: true
  49390. });
  49391. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  49392. get: function () {
  49393. return this._dPadDown;
  49394. },
  49395. set: function (value) {
  49396. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  49397. },
  49398. enumerable: true,
  49399. configurable: true
  49400. });
  49401. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  49402. get: function () {
  49403. return this._dPadLeft;
  49404. },
  49405. set: function (value) {
  49406. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  49407. },
  49408. enumerable: true,
  49409. configurable: true
  49410. });
  49411. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  49412. get: function () {
  49413. return this._dPadRight;
  49414. },
  49415. set: function (value) {
  49416. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  49417. },
  49418. enumerable: true,
  49419. configurable: true
  49420. });
  49421. Xbox360Pad.prototype.update = function () {
  49422. _super.prototype.update.call(this);
  49423. if (this._isXboxOnePad) {
  49424. this.buttonA = this.browserGamepad.buttons[0].value;
  49425. this.buttonB = this.browserGamepad.buttons[1].value;
  49426. this.buttonX = this.browserGamepad.buttons[2].value;
  49427. this.buttonY = this.browserGamepad.buttons[3].value;
  49428. this.buttonLB = this.browserGamepad.buttons[4].value;
  49429. this.buttonRB = this.browserGamepad.buttons[5].value;
  49430. this.leftTrigger = this.browserGamepad.axes[2];
  49431. this.rightTrigger = this.browserGamepad.axes[5];
  49432. this.buttonBack = this.browserGamepad.buttons[9].value;
  49433. this.buttonStart = this.browserGamepad.buttons[8].value;
  49434. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  49435. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  49436. this.dPadUp = this.browserGamepad.buttons[11].value;
  49437. this.dPadDown = this.browserGamepad.buttons[12].value;
  49438. this.dPadLeft = this.browserGamepad.buttons[13].value;
  49439. this.dPadRight = this.browserGamepad.buttons[14].value;
  49440. }
  49441. else {
  49442. this.buttonA = this.browserGamepad.buttons[0].value;
  49443. this.buttonB = this.browserGamepad.buttons[1].value;
  49444. this.buttonX = this.browserGamepad.buttons[2].value;
  49445. this.buttonY = this.browserGamepad.buttons[3].value;
  49446. this.buttonLB = this.browserGamepad.buttons[4].value;
  49447. this.buttonRB = this.browserGamepad.buttons[5].value;
  49448. this.leftTrigger = this.browserGamepad.buttons[6].value;
  49449. this.rightTrigger = this.browserGamepad.buttons[7].value;
  49450. this.buttonBack = this.browserGamepad.buttons[8].value;
  49451. this.buttonStart = this.browserGamepad.buttons[9].value;
  49452. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  49453. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  49454. this.dPadUp = this.browserGamepad.buttons[12].value;
  49455. this.dPadDown = this.browserGamepad.buttons[13].value;
  49456. this.dPadLeft = this.browserGamepad.buttons[14].value;
  49457. this.dPadRight = this.browserGamepad.buttons[15].value;
  49458. }
  49459. };
  49460. return Xbox360Pad;
  49461. }(Gamepad));
  49462. BABYLON.Xbox360Pad = Xbox360Pad;
  49463. })(BABYLON || (BABYLON = {}));
  49464. //# sourceMappingURL=babylon.gamepads.js.map
  49465. var BABYLON;
  49466. (function (BABYLON) {
  49467. var PoseEnabledControllerType;
  49468. (function (PoseEnabledControllerType) {
  49469. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  49470. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  49471. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  49472. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  49473. var PoseEnabledControllerHelper = (function () {
  49474. function PoseEnabledControllerHelper() {
  49475. }
  49476. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  49477. // for now, only Oculus and Vive are supported
  49478. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  49479. return new OculusTouchController(vrGamepad);
  49480. }
  49481. else {
  49482. return new ViveController(vrGamepad);
  49483. }
  49484. };
  49485. return PoseEnabledControllerHelper;
  49486. }());
  49487. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  49488. var PoseEnabledController = (function (_super) {
  49489. __extends(PoseEnabledController, _super);
  49490. function PoseEnabledController(vrGamepad) {
  49491. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  49492. _this.vrGamepad = vrGamepad;
  49493. _this.deviceScaleFactor = 1;
  49494. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  49495. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  49496. _this.controllerType = PoseEnabledControllerType.GENERIC;
  49497. _this.position = BABYLON.Vector3.Zero();
  49498. _this.rotationQuaternion = new BABYLON.Quaternion();
  49499. _this.devicePosition = BABYLON.Vector3.Zero();
  49500. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  49501. _this._calculatedPosition = BABYLON.Vector3.Zero();
  49502. _this._calculatedRotation = new BABYLON.Quaternion();
  49503. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  49504. return _this;
  49505. }
  49506. PoseEnabledController.prototype.update = function () {
  49507. _super.prototype.update.call(this);
  49508. var pose = this.vrGamepad.pose;
  49509. this.updateFromDevice(pose);
  49510. if (this._mesh) {
  49511. this._mesh.position.copyFrom(this._calculatedPosition);
  49512. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  49513. }
  49514. };
  49515. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  49516. if (poseData) {
  49517. this.rawPose = poseData;
  49518. if (poseData.position) {
  49519. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  49520. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  49521. this.devicePosition.z *= -1;
  49522. }
  49523. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  49524. this._calculatedPosition.addInPlace(this.position);
  49525. }
  49526. if (poseData.orientation) {
  49527. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  49528. if (this._mesh) {
  49529. if (this._mesh.getScene().useRightHandedSystem) {
  49530. this.deviceRotationQuaternion.z *= -1;
  49531. this.deviceRotationQuaternion.w *= -1;
  49532. }
  49533. else {
  49534. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  49535. }
  49536. }
  49537. // if the camera is set, rotate to the camera's rotation
  49538. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  49539. }
  49540. }
  49541. };
  49542. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  49543. if (this._mesh) {
  49544. this._mesh.parent = undefined;
  49545. }
  49546. this._mesh = mesh;
  49547. if (this._poseControlledCamera) {
  49548. this._mesh.parent = this._poseControlledCamera;
  49549. }
  49550. if (!this._mesh.rotationQuaternion) {
  49551. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  49552. }
  49553. };
  49554. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  49555. this._poseControlledCamera = camera;
  49556. if (this._mesh) {
  49557. this._mesh.parent = this._poseControlledCamera;
  49558. }
  49559. };
  49560. PoseEnabledController.prototype.detachMesh = function () {
  49561. this._mesh = undefined;
  49562. };
  49563. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  49564. get: function () {
  49565. return this._mesh;
  49566. },
  49567. enumerable: true,
  49568. configurable: true
  49569. });
  49570. PoseEnabledController.prototype.getForwardRay = function (length) {
  49571. if (length === void 0) { length = 100; }
  49572. if (!this.mesh) {
  49573. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  49574. }
  49575. var m = this.mesh.getWorldMatrix();
  49576. var origin = m.getTranslation();
  49577. var forward = new BABYLON.Vector3(0, 0, -1);
  49578. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  49579. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  49580. return new BABYLON.Ray(origin, direction, length);
  49581. };
  49582. return PoseEnabledController;
  49583. }(BABYLON.Gamepad));
  49584. BABYLON.PoseEnabledController = PoseEnabledController;
  49585. var WebVRController = (function (_super) {
  49586. __extends(WebVRController, _super);
  49587. function WebVRController(vrGamepad) {
  49588. var _this = _super.call(this, vrGamepad) || this;
  49589. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  49590. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  49591. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  49592. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  49593. _this.onPadStateChangedObservable = new BABYLON.Observable();
  49594. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  49595. _this.pad = { x: 0, y: 0 };
  49596. // avoid GC, store state in a tmp object
  49597. _this._changes = {
  49598. pressChanged: false,
  49599. touchChanged: false,
  49600. valueChanged: false,
  49601. changed: false
  49602. };
  49603. _this._buttons = new Array(vrGamepad.buttons.length);
  49604. _this.hand = vrGamepad.hand;
  49605. return _this;
  49606. }
  49607. WebVRController.prototype.onButtonStateChange = function (callback) {
  49608. this._onButtonStateChange = callback;
  49609. };
  49610. WebVRController.prototype.update = function () {
  49611. _super.prototype.update.call(this);
  49612. for (var index = 0; index < this._buttons.length; index++) {
  49613. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  49614. }
  49615. ;
  49616. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  49617. this.pad.x = this.leftStick.x;
  49618. this.pad.y = this.leftStick.y;
  49619. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  49620. }
  49621. };
  49622. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  49623. if (!currentState) {
  49624. this._buttons[buttonIndex] = {
  49625. pressed: newState.pressed,
  49626. touched: newState.touched,
  49627. value: newState.value
  49628. };
  49629. return;
  49630. }
  49631. this._checkChanges(newState, currentState);
  49632. if (this._changes.changed) {
  49633. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  49634. this.handleButtonChange(buttonIndex, newState, this._changes);
  49635. }
  49636. this._buttons[buttonIndex].pressed = newState.pressed;
  49637. this._buttons[buttonIndex].touched = newState.touched;
  49638. // oculus triggers are never 0, thou not touched.
  49639. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  49640. };
  49641. WebVRController.prototype._checkChanges = function (newState, currentState) {
  49642. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  49643. this._changes.touchChanged = newState.touched !== currentState.touched;
  49644. this._changes.valueChanged = newState.value !== currentState.value;
  49645. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  49646. return this._changes;
  49647. };
  49648. return WebVRController;
  49649. }(PoseEnabledController));
  49650. BABYLON.WebVRController = WebVRController;
  49651. var OculusTouchController = (function (_super) {
  49652. __extends(OculusTouchController, _super);
  49653. function OculusTouchController(vrGamepad) {
  49654. var _this = _super.call(this, vrGamepad) || this;
  49655. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  49656. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  49657. _this.controllerType = PoseEnabledControllerType.OCULUS;
  49658. return _this;
  49659. }
  49660. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  49661. var _this = this;
  49662. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  49663. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  49664. /*
  49665. Parent Mesh name: oculus_touch_left
  49666. - body
  49667. - trigger
  49668. - thumbstick
  49669. - grip
  49670. - button_y
  49671. - button_x
  49672. - button_enter
  49673. */
  49674. _this._defaultModel = newMeshes[1];
  49675. if (meshLoaded) {
  49676. meshLoaded(_this._defaultModel);
  49677. }
  49678. _this.attachToMesh(_this._defaultModel);
  49679. });
  49680. };
  49681. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  49682. // helper getters for left and right hand.
  49683. get: function () {
  49684. if (this.hand === 'right') {
  49685. return this.onMainButtonStateChangedObservable;
  49686. }
  49687. else {
  49688. throw new Error('No A button on left hand');
  49689. }
  49690. },
  49691. enumerable: true,
  49692. configurable: true
  49693. });
  49694. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  49695. get: function () {
  49696. if (this.hand === 'right') {
  49697. return this.onSecondaryButtonStateChangedObservable;
  49698. }
  49699. else {
  49700. throw new Error('No B button on left hand');
  49701. }
  49702. },
  49703. enumerable: true,
  49704. configurable: true
  49705. });
  49706. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  49707. get: function () {
  49708. if (this.hand === 'left') {
  49709. return this.onMainButtonStateChangedObservable;
  49710. }
  49711. else {
  49712. throw new Error('No X button on right hand');
  49713. }
  49714. },
  49715. enumerable: true,
  49716. configurable: true
  49717. });
  49718. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  49719. get: function () {
  49720. if (this.hand === 'left') {
  49721. return this.onSecondaryButtonStateChangedObservable;
  49722. }
  49723. else {
  49724. throw new Error('No Y button on right hand');
  49725. }
  49726. },
  49727. enumerable: true,
  49728. configurable: true
  49729. });
  49730. /*
  49731. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  49732. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  49733. 2) secondary trigger (same)
  49734. 3) A (right) X (left), touch, pressed = value
  49735. 4) B / Y
  49736. 5) thumb rest
  49737. */
  49738. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  49739. var notifyObject = state; //{ state: state, changes: changes };
  49740. var triggerDirection = this.hand === 'right' ? -1 : 1;
  49741. switch (buttonIdx) {
  49742. case 0:
  49743. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  49744. return;
  49745. case 1:
  49746. if (this._defaultModel) {
  49747. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  49748. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  49749. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  49750. }
  49751. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  49752. return;
  49753. case 2:
  49754. if (this._defaultModel) {
  49755. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  49756. }
  49757. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  49758. return;
  49759. case 3:
  49760. if (this._defaultModel) {
  49761. if (notifyObject.pressed) {
  49762. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  49763. }
  49764. else {
  49765. (this._defaultModel.getChildren()[1]).position.y = 0;
  49766. }
  49767. }
  49768. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  49769. return;
  49770. case 4:
  49771. if (this._defaultModel) {
  49772. if (notifyObject.pressed) {
  49773. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  49774. }
  49775. else {
  49776. (this._defaultModel.getChildren()[2]).position.y = 0;
  49777. }
  49778. }
  49779. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  49780. return;
  49781. case 5:
  49782. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  49783. return;
  49784. }
  49785. };
  49786. return OculusTouchController;
  49787. }(WebVRController));
  49788. BABYLON.OculusTouchController = OculusTouchController;
  49789. var ViveController = (function (_super) {
  49790. __extends(ViveController, _super);
  49791. function ViveController(vrGamepad) {
  49792. var _this = _super.call(this, vrGamepad) || this;
  49793. _this.controllerType = PoseEnabledControllerType.VIVE;
  49794. return _this;
  49795. }
  49796. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  49797. var _this = this;
  49798. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  49799. /*
  49800. Parent Mesh name: ViveWand
  49801. - body
  49802. - r_gripper
  49803. - l_gripper
  49804. - menu_button
  49805. - system_button
  49806. - trackpad
  49807. - trigger
  49808. - LED
  49809. */
  49810. _this._defaultModel = newMeshes[1];
  49811. if (meshLoaded) {
  49812. meshLoaded(_this._defaultModel);
  49813. }
  49814. _this.attachToMesh(_this._defaultModel);
  49815. });
  49816. };
  49817. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  49818. get: function () {
  49819. return this.onMainButtonStateChangedObservable;
  49820. },
  49821. enumerable: true,
  49822. configurable: true
  49823. });
  49824. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  49825. get: function () {
  49826. return this.onMainButtonStateChangedObservable;
  49827. },
  49828. enumerable: true,
  49829. configurable: true
  49830. });
  49831. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  49832. get: function () {
  49833. return this.onSecondaryButtonStateChangedObservable;
  49834. },
  49835. enumerable: true,
  49836. configurable: true
  49837. });
  49838. /**
  49839. * Vive mapping:
  49840. * 0: touchpad
  49841. * 1: trigger
  49842. * 2: left AND right buttons
  49843. * 3: menu button
  49844. */
  49845. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  49846. var notifyObject = state; //{ state: state, changes: changes };
  49847. switch (buttonIdx) {
  49848. case 0:
  49849. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  49850. return;
  49851. case 1:
  49852. if (this._defaultModel) {
  49853. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  49854. }
  49855. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  49856. return;
  49857. case 2:
  49858. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  49859. return;
  49860. case 3:
  49861. if (this._defaultModel) {
  49862. if (notifyObject.pressed) {
  49863. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  49864. }
  49865. else {
  49866. (this._defaultModel.getChildren()[2]).position.y = 0;
  49867. }
  49868. }
  49869. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  49870. return;
  49871. }
  49872. };
  49873. return ViveController;
  49874. }(WebVRController));
  49875. BABYLON.ViveController = ViveController;
  49876. })(BABYLON || (BABYLON = {}));
  49877. //# sourceMappingURL=babylon.extendedGamepad.js.map
  49878. /// <reference path="babylon.targetCamera.ts" />
  49879. var BABYLON;
  49880. (function (BABYLON) {
  49881. var FollowCamera = (function (_super) {
  49882. __extends(FollowCamera, _super);
  49883. function FollowCamera(name, position, scene, lockedTarget) {
  49884. var _this = _super.call(this, name, position, scene) || this;
  49885. _this.radius = 12;
  49886. _this.rotationOffset = 0;
  49887. _this.heightOffset = 4;
  49888. _this.cameraAcceleration = 0.05;
  49889. _this.maxCameraSpeed = 20;
  49890. _this.lockedTarget = lockedTarget;
  49891. return _this;
  49892. }
  49893. FollowCamera.prototype.getRadians = function (degrees) {
  49894. return degrees * Math.PI / 180;
  49895. };
  49896. FollowCamera.prototype.follow = function (cameraTarget) {
  49897. if (!cameraTarget)
  49898. return;
  49899. var yRotation;
  49900. if (cameraTarget.rotationQuaternion) {
  49901. var rotMatrix = new BABYLON.Matrix();
  49902. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  49903. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  49904. }
  49905. else {
  49906. yRotation = cameraTarget.rotation.y;
  49907. }
  49908. var radians = this.getRadians(this.rotationOffset) + yRotation;
  49909. var targetPosition = cameraTarget.getAbsolutePosition();
  49910. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  49911. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  49912. var dx = targetX - this.position.x;
  49913. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  49914. var dz = (targetZ) - this.position.z;
  49915. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  49916. var vy = dy * this.cameraAcceleration;
  49917. var vz = dz * this.cameraAcceleration * 2;
  49918. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  49919. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49920. }
  49921. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  49922. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49923. }
  49924. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  49925. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49926. }
  49927. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  49928. this.setTarget(targetPosition);
  49929. };
  49930. FollowCamera.prototype._checkInputs = function () {
  49931. _super.prototype._checkInputs.call(this);
  49932. this.follow(this.lockedTarget);
  49933. };
  49934. FollowCamera.prototype.getClassName = function () {
  49935. return "FollowCamera";
  49936. };
  49937. return FollowCamera;
  49938. }(BABYLON.TargetCamera));
  49939. __decorate([
  49940. BABYLON.serialize()
  49941. ], FollowCamera.prototype, "radius", void 0);
  49942. __decorate([
  49943. BABYLON.serialize()
  49944. ], FollowCamera.prototype, "rotationOffset", void 0);
  49945. __decorate([
  49946. BABYLON.serialize()
  49947. ], FollowCamera.prototype, "heightOffset", void 0);
  49948. __decorate([
  49949. BABYLON.serialize()
  49950. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  49951. __decorate([
  49952. BABYLON.serialize()
  49953. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  49954. __decorate([
  49955. BABYLON.serializeAsMeshReference("lockedTargetId")
  49956. ], FollowCamera.prototype, "lockedTarget", void 0);
  49957. BABYLON.FollowCamera = FollowCamera;
  49958. var ArcFollowCamera = (function (_super) {
  49959. __extends(ArcFollowCamera, _super);
  49960. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  49961. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  49962. _this.alpha = alpha;
  49963. _this.beta = beta;
  49964. _this.radius = radius;
  49965. _this.target = target;
  49966. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  49967. _this.follow();
  49968. return _this;
  49969. }
  49970. ArcFollowCamera.prototype.follow = function () {
  49971. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  49972. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  49973. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  49974. var targetPosition = this.target.getAbsolutePosition();
  49975. this.position = targetPosition.add(this._cartesianCoordinates);
  49976. this.setTarget(targetPosition);
  49977. };
  49978. ArcFollowCamera.prototype._checkInputs = function () {
  49979. _super.prototype._checkInputs.call(this);
  49980. this.follow();
  49981. };
  49982. ArcFollowCamera.prototype.getClassName = function () {
  49983. return "ArcFollowCamera";
  49984. };
  49985. return ArcFollowCamera;
  49986. }(BABYLON.TargetCamera));
  49987. BABYLON.ArcFollowCamera = ArcFollowCamera;
  49988. })(BABYLON || (BABYLON = {}));
  49989. //# sourceMappingURL=babylon.followCamera.js.map
  49990. /// <reference path="babylon.touchCamera.ts" />
  49991. var BABYLON;
  49992. (function (BABYLON) {
  49993. // We're mainly based on the logic defined into the FreeCamera code
  49994. var UniversalCamera = (function (_super) {
  49995. __extends(UniversalCamera, _super);
  49996. //-- end properties for backward compatibility for inputs
  49997. function UniversalCamera(name, position, scene) {
  49998. var _this = _super.call(this, name, position, scene) || this;
  49999. _this.inputs.addGamepad();
  50000. return _this;
  50001. }
  50002. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  50003. //-- Begin properties for backward compatibility for inputs
  50004. get: function () {
  50005. var gamepad = this.inputs.attached["gamepad"];
  50006. if (gamepad)
  50007. return gamepad.gamepadAngularSensibility;
  50008. },
  50009. set: function (value) {
  50010. var gamepad = this.inputs.attached["gamepad"];
  50011. if (gamepad)
  50012. gamepad.gamepadAngularSensibility = value;
  50013. },
  50014. enumerable: true,
  50015. configurable: true
  50016. });
  50017. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  50018. get: function () {
  50019. var gamepad = this.inputs.attached["gamepad"];
  50020. if (gamepad)
  50021. return gamepad.gamepadMoveSensibility;
  50022. },
  50023. set: function (value) {
  50024. var gamepad = this.inputs.attached["gamepad"];
  50025. if (gamepad)
  50026. gamepad.gamepadMoveSensibility = value;
  50027. },
  50028. enumerable: true,
  50029. configurable: true
  50030. });
  50031. UniversalCamera.prototype.getClassName = function () {
  50032. return "UniversalCamera";
  50033. };
  50034. return UniversalCamera;
  50035. }(BABYLON.TouchCamera));
  50036. BABYLON.UniversalCamera = UniversalCamera;
  50037. })(BABYLON || (BABYLON = {}));
  50038. //# sourceMappingURL=babylon.universalCamera.js.map
  50039. /// <reference path="babylon.universalCamera.ts" />
  50040. var BABYLON;
  50041. (function (BABYLON) {
  50042. // We're mainly based on the logic defined into the FreeCamera code
  50043. var GamepadCamera = (function (_super) {
  50044. __extends(GamepadCamera, _super);
  50045. //-- end properties for backward compatibility for inputs
  50046. function GamepadCamera(name, position, scene) {
  50047. return _super.call(this, name, position, scene) || this;
  50048. }
  50049. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  50050. //-- Begin properties for backward compatibility for inputs
  50051. get: function () {
  50052. var gamepad = this.inputs.attached["gamepad"];
  50053. if (gamepad)
  50054. return gamepad.gamepadAngularSensibility;
  50055. },
  50056. set: function (value) {
  50057. var gamepad = this.inputs.attached["gamepad"];
  50058. if (gamepad)
  50059. gamepad.gamepadAngularSensibility = value;
  50060. },
  50061. enumerable: true,
  50062. configurable: true
  50063. });
  50064. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  50065. get: function () {
  50066. var gamepad = this.inputs.attached["gamepad"];
  50067. if (gamepad)
  50068. return gamepad.gamepadMoveSensibility;
  50069. },
  50070. set: function (value) {
  50071. var gamepad = this.inputs.attached["gamepad"];
  50072. if (gamepad)
  50073. gamepad.gamepadMoveSensibility = value;
  50074. },
  50075. enumerable: true,
  50076. configurable: true
  50077. });
  50078. GamepadCamera.prototype.getClassName = function () {
  50079. return "GamepadCamera";
  50080. };
  50081. return GamepadCamera;
  50082. }(BABYLON.UniversalCamera));
  50083. BABYLON.GamepadCamera = GamepadCamera;
  50084. })(BABYLON || (BABYLON = {}));
  50085. //# sourceMappingURL=babylon.gamepadCamera.js.map
  50086. var BABYLON;
  50087. (function (BABYLON) {
  50088. var PostProcessRenderPipelineManager = (function () {
  50089. function PostProcessRenderPipelineManager() {
  50090. this._renderPipelines = {};
  50091. }
  50092. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  50093. this._renderPipelines[renderPipeline._name] = renderPipeline;
  50094. };
  50095. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  50096. var renderPipeline = this._renderPipelines[renderPipelineName];
  50097. if (!renderPipeline) {
  50098. return;
  50099. }
  50100. renderPipeline._attachCameras(cameras, unique);
  50101. };
  50102. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  50103. var renderPipeline = this._renderPipelines[renderPipelineName];
  50104. if (!renderPipeline) {
  50105. return;
  50106. }
  50107. renderPipeline._detachCameras(cameras);
  50108. };
  50109. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  50110. var renderPipeline = this._renderPipelines[renderPipelineName];
  50111. if (!renderPipeline) {
  50112. return;
  50113. }
  50114. renderPipeline._enableEffect(renderEffectName, cameras);
  50115. };
  50116. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  50117. var renderPipeline = this._renderPipelines[renderPipelineName];
  50118. if (!renderPipeline) {
  50119. return;
  50120. }
  50121. renderPipeline._disableEffect(renderEffectName, cameras);
  50122. };
  50123. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  50124. var renderPipeline = this._renderPipelines[renderPipelineName];
  50125. if (!renderPipeline) {
  50126. return;
  50127. }
  50128. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  50129. };
  50130. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  50131. var renderPipeline = this._renderPipelines[renderPipelineName];
  50132. if (!renderPipeline) {
  50133. return;
  50134. }
  50135. renderPipeline._disableDisplayOnlyPass(cameras);
  50136. };
  50137. PostProcessRenderPipelineManager.prototype.update = function () {
  50138. for (var renderPipelineName in this._renderPipelines) {
  50139. var pipeline = this._renderPipelines[renderPipelineName];
  50140. if (!pipeline.isSupported) {
  50141. pipeline.dispose();
  50142. delete this._renderPipelines[renderPipelineName];
  50143. }
  50144. else {
  50145. pipeline._update();
  50146. }
  50147. }
  50148. };
  50149. return PostProcessRenderPipelineManager;
  50150. }());
  50151. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  50152. })(BABYLON || (BABYLON = {}));
  50153. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  50154. var BABYLON;
  50155. (function (BABYLON) {
  50156. var PostProcessRenderPass = (function () {
  50157. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  50158. this._enabled = true;
  50159. this._refCount = 0;
  50160. this._name = name;
  50161. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  50162. this.setRenderList(renderList);
  50163. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  50164. this._renderTexture.onAfterRenderObservable.add(afterRender);
  50165. this._scene = scene;
  50166. this._renderList = renderList;
  50167. }
  50168. // private
  50169. PostProcessRenderPass.prototype._incRefCount = function () {
  50170. if (this._refCount === 0) {
  50171. this._scene.customRenderTargets.push(this._renderTexture);
  50172. }
  50173. return ++this._refCount;
  50174. };
  50175. PostProcessRenderPass.prototype._decRefCount = function () {
  50176. this._refCount--;
  50177. if (this._refCount <= 0) {
  50178. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  50179. }
  50180. return this._refCount;
  50181. };
  50182. PostProcessRenderPass.prototype._update = function () {
  50183. this.setRenderList(this._renderList);
  50184. };
  50185. // public
  50186. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  50187. this._renderTexture.renderList = renderList;
  50188. };
  50189. PostProcessRenderPass.prototype.getRenderTexture = function () {
  50190. return this._renderTexture;
  50191. };
  50192. return PostProcessRenderPass;
  50193. }());
  50194. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  50195. })(BABYLON || (BABYLON = {}));
  50196. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  50197. var BABYLON;
  50198. (function (BABYLON) {
  50199. var PostProcessRenderEffect = (function () {
  50200. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  50201. this._engine = engine;
  50202. this._name = name;
  50203. this._singleInstance = singleInstance || true;
  50204. this._getPostProcess = getPostProcess;
  50205. this._cameras = [];
  50206. this._indicesForCamera = [];
  50207. this._postProcesses = {};
  50208. this._renderPasses = {};
  50209. this._renderEffectAsPasses = {};
  50210. }
  50211. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  50212. get: function () {
  50213. for (var index in this._postProcesses) {
  50214. if (!this._postProcesses[index].isSupported) {
  50215. return false;
  50216. }
  50217. }
  50218. return true;
  50219. },
  50220. enumerable: true,
  50221. configurable: true
  50222. });
  50223. PostProcessRenderEffect.prototype._update = function () {
  50224. for (var renderPassName in this._renderPasses) {
  50225. this._renderPasses[renderPassName]._update();
  50226. }
  50227. };
  50228. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  50229. this._renderPasses[renderPass._name] = renderPass;
  50230. this._linkParameters();
  50231. };
  50232. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  50233. delete this._renderPasses[renderPass._name];
  50234. this._linkParameters();
  50235. };
  50236. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  50237. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  50238. this._linkParameters();
  50239. };
  50240. PostProcessRenderEffect.prototype.getPass = function (passName) {
  50241. for (var renderPassName in this._renderPasses) {
  50242. if (renderPassName === passName) {
  50243. return this._renderPasses[passName];
  50244. }
  50245. }
  50246. };
  50247. PostProcessRenderEffect.prototype.emptyPasses = function () {
  50248. this._renderPasses = {};
  50249. this._linkParameters();
  50250. };
  50251. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  50252. var cameraKey;
  50253. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50254. for (var i = 0; i < _cam.length; i++) {
  50255. var camera = _cam[i];
  50256. var cameraName = camera.name;
  50257. if (this._singleInstance) {
  50258. cameraKey = 0;
  50259. }
  50260. else {
  50261. cameraKey = cameraName;
  50262. }
  50263. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  50264. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  50265. if (!this._indicesForCamera[cameraName]) {
  50266. this._indicesForCamera[cameraName] = [];
  50267. }
  50268. this._indicesForCamera[cameraName].push(index);
  50269. if (this._cameras.indexOf(camera) === -1) {
  50270. this._cameras[cameraName] = camera;
  50271. }
  50272. for (var passName in this._renderPasses) {
  50273. this._renderPasses[passName]._incRefCount();
  50274. }
  50275. }
  50276. this._linkParameters();
  50277. };
  50278. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  50279. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50280. for (var i = 0; i < _cam.length; i++) {
  50281. var camera = _cam[i];
  50282. var cameraName = camera.name;
  50283. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  50284. var index = this._cameras.indexOf(cameraName);
  50285. this._indicesForCamera.splice(index, 1);
  50286. this._cameras.splice(index, 1);
  50287. for (var passName in this._renderPasses) {
  50288. this._renderPasses[passName]._decRefCount();
  50289. }
  50290. }
  50291. };
  50292. PostProcessRenderEffect.prototype._enable = function (cameras) {
  50293. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50294. for (var i = 0; i < _cam.length; i++) {
  50295. var camera = _cam[i];
  50296. var cameraName = camera.name;
  50297. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  50298. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  50299. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  50300. }
  50301. }
  50302. for (var passName in this._renderPasses) {
  50303. this._renderPasses[passName]._incRefCount();
  50304. }
  50305. }
  50306. };
  50307. PostProcessRenderEffect.prototype._disable = function (cameras) {
  50308. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50309. for (var i = 0; i < _cam.length; i++) {
  50310. var camera = _cam[i];
  50311. var cameraName = camera.Name;
  50312. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  50313. for (var passName in this._renderPasses) {
  50314. this._renderPasses[passName]._decRefCount();
  50315. }
  50316. }
  50317. };
  50318. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  50319. if (this._singleInstance) {
  50320. return this._postProcesses[0];
  50321. }
  50322. else {
  50323. return this._postProcesses[camera.name];
  50324. }
  50325. };
  50326. PostProcessRenderEffect.prototype._linkParameters = function () {
  50327. var _this = this;
  50328. for (var index in this._postProcesses) {
  50329. if (this.applyParameters) {
  50330. this.applyParameters(this._postProcesses[index]);
  50331. }
  50332. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  50333. _this._linkTextures(effect);
  50334. });
  50335. }
  50336. };
  50337. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  50338. for (var renderPassName in this._renderPasses) {
  50339. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  50340. }
  50341. for (var renderEffectName in this._renderEffectAsPasses) {
  50342. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  50343. }
  50344. };
  50345. return PostProcessRenderEffect;
  50346. }());
  50347. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  50348. })(BABYLON || (BABYLON = {}));
  50349. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  50350. var BABYLON;
  50351. (function (BABYLON) {
  50352. var PostProcessRenderPipeline = (function () {
  50353. function PostProcessRenderPipeline(engine, name) {
  50354. this._engine = engine;
  50355. this._name = name;
  50356. this._renderEffects = new Array();
  50357. this._renderEffectsForIsolatedPass = new Array();
  50358. this._cameras = [];
  50359. }
  50360. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  50361. get: function () {
  50362. for (var renderEffectName in this._renderEffects) {
  50363. if (!this._renderEffects[renderEffectName].isSupported) {
  50364. return false;
  50365. }
  50366. }
  50367. return true;
  50368. },
  50369. enumerable: true,
  50370. configurable: true
  50371. });
  50372. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  50373. this._renderEffects[renderEffect._name] = renderEffect;
  50374. };
  50375. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  50376. var renderEffects = this._renderEffects[renderEffectName];
  50377. if (!renderEffects) {
  50378. return;
  50379. }
  50380. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  50381. };
  50382. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  50383. var renderEffects = this._renderEffects[renderEffectName];
  50384. if (!renderEffects) {
  50385. return;
  50386. }
  50387. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  50388. };
  50389. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  50390. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50391. var indicesToDelete = [];
  50392. var i;
  50393. for (i = 0; i < _cam.length; i++) {
  50394. var camera = _cam[i];
  50395. var cameraName = camera.name;
  50396. if (this._cameras.indexOf(camera) === -1) {
  50397. this._cameras[cameraName] = camera;
  50398. }
  50399. else if (unique) {
  50400. indicesToDelete.push(i);
  50401. }
  50402. }
  50403. for (i = 0; i < indicesToDelete.length; i++) {
  50404. cameras.splice(indicesToDelete[i], 1);
  50405. }
  50406. for (var renderEffectName in this._renderEffects) {
  50407. this._renderEffects[renderEffectName]._attachCameras(_cam);
  50408. }
  50409. };
  50410. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  50411. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50412. for (var renderEffectName in this._renderEffects) {
  50413. this._renderEffects[renderEffectName]._detachCameras(_cam);
  50414. }
  50415. for (var i = 0; i < _cam.length; i++) {
  50416. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  50417. }
  50418. };
  50419. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  50420. var _this = this;
  50421. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50422. var pass = null;
  50423. var renderEffectName;
  50424. for (renderEffectName in this._renderEffects) {
  50425. pass = this._renderEffects[renderEffectName].getPass(passName);
  50426. if (pass != null) {
  50427. break;
  50428. }
  50429. }
  50430. if (pass === null) {
  50431. return;
  50432. }
  50433. for (renderEffectName in this._renderEffects) {
  50434. this._renderEffects[renderEffectName]._disable(_cam);
  50435. }
  50436. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  50437. for (var i = 0; i < _cam.length; i++) {
  50438. var camera = _cam[i];
  50439. var cameraName = camera.name;
  50440. 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); });
  50441. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  50442. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  50443. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  50444. }
  50445. };
  50446. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  50447. var _this = this;
  50448. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50449. for (var i = 0; i < _cam.length; i++) {
  50450. var camera = _cam[i];
  50451. var cameraName = camera.name;
  50452. 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); });
  50453. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  50454. }
  50455. for (var renderEffectName in this._renderEffects) {
  50456. this._renderEffects[renderEffectName]._enable(_cam);
  50457. }
  50458. };
  50459. PostProcessRenderPipeline.prototype._update = function () {
  50460. for (var renderEffectName in this._renderEffects) {
  50461. this._renderEffects[renderEffectName]._update();
  50462. }
  50463. for (var i = 0; i < this._cameras.length; i++) {
  50464. var cameraName = this._cameras[i].name;
  50465. if (this._renderEffectsForIsolatedPass[cameraName]) {
  50466. this._renderEffectsForIsolatedPass[cameraName]._update();
  50467. }
  50468. }
  50469. };
  50470. PostProcessRenderPipeline.prototype._reset = function () {
  50471. this._renderEffects = new Array();
  50472. this._renderEffectsForIsolatedPass = new Array();
  50473. };
  50474. PostProcessRenderPipeline.prototype.dispose = function () {
  50475. // Must be implemented by children
  50476. };
  50477. return PostProcessRenderPipeline;
  50478. }());
  50479. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  50480. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  50481. __decorate([
  50482. BABYLON.serialize()
  50483. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  50484. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  50485. })(BABYLON || (BABYLON = {}));
  50486. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  50487. var BABYLON;
  50488. (function (BABYLON) {
  50489. var DepthRenderer = (function () {
  50490. function DepthRenderer(scene, type) {
  50491. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  50492. var _this = this;
  50493. this._viewMatrix = BABYLON.Matrix.Zero();
  50494. this._projectionMatrix = BABYLON.Matrix.Zero();
  50495. this._transformMatrix = BABYLON.Matrix.Zero();
  50496. this._worldViewProjection = BABYLON.Matrix.Zero();
  50497. this._scene = scene;
  50498. var engine = scene.getEngine();
  50499. // Render target
  50500. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  50501. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50502. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50503. this._depthMap.refreshRate = 1;
  50504. this._depthMap.renderParticles = false;
  50505. this._depthMap.renderList = null;
  50506. // set default depth value to 1.0 (far away)
  50507. this._depthMap.onClearObservable.add(function (engine) {
  50508. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  50509. });
  50510. // Custom render function
  50511. var renderSubMesh = function (subMesh) {
  50512. var mesh = subMesh.getRenderingMesh();
  50513. var scene = _this._scene;
  50514. var engine = scene.getEngine();
  50515. // Culling
  50516. engine.setState(subMesh.getMaterial().backFaceCulling);
  50517. // Managing instances
  50518. var batch = mesh._getInstancesRenderList(subMesh._id);
  50519. if (batch.mustReturn) {
  50520. return;
  50521. }
  50522. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  50523. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50524. engine.enableEffect(_this._effect);
  50525. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  50526. var material = subMesh.getMaterial();
  50527. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50528. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  50529. // Alpha test
  50530. if (material && material.needAlphaTesting()) {
  50531. var alphaTexture = material.getAlphaTestTexture();
  50532. _this._effect.setTexture("diffuseSampler", alphaTexture);
  50533. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50534. }
  50535. // Bones
  50536. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50537. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50538. }
  50539. // Draw
  50540. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  50541. }
  50542. };
  50543. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  50544. var index;
  50545. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50546. renderSubMesh(opaqueSubMeshes.data[index]);
  50547. }
  50548. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50549. renderSubMesh(alphaTestSubMeshes.data[index]);
  50550. }
  50551. };
  50552. }
  50553. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  50554. var material = subMesh.getMaterial();
  50555. if (material.disableDepthWrite) {
  50556. return false;
  50557. }
  50558. var defines = [];
  50559. var attribs = [BABYLON.VertexBuffer.PositionKind];
  50560. var mesh = subMesh.getMesh();
  50561. var scene = mesh.getScene();
  50562. // Alpha test
  50563. if (material && material.needAlphaTesting()) {
  50564. defines.push("#define ALPHATEST");
  50565. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50566. attribs.push(BABYLON.VertexBuffer.UVKind);
  50567. defines.push("#define UV1");
  50568. }
  50569. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50570. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50571. defines.push("#define UV2");
  50572. }
  50573. }
  50574. // Bones
  50575. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50576. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50577. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50578. if (mesh.numBoneInfluencers > 4) {
  50579. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50580. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50581. }
  50582. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50583. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50584. }
  50585. else {
  50586. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50587. }
  50588. // Instances
  50589. if (useInstances) {
  50590. defines.push("#define INSTANCES");
  50591. attribs.push("world0");
  50592. attribs.push("world1");
  50593. attribs.push("world2");
  50594. attribs.push("world3");
  50595. }
  50596. // Get correct effect
  50597. var join = defines.join("\n");
  50598. if (this._cachedDefines !== join) {
  50599. this._cachedDefines = join;
  50600. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  50601. }
  50602. return this._effect.isReady();
  50603. };
  50604. DepthRenderer.prototype.getDepthMap = function () {
  50605. return this._depthMap;
  50606. };
  50607. // Methods
  50608. DepthRenderer.prototype.dispose = function () {
  50609. this._depthMap.dispose();
  50610. };
  50611. return DepthRenderer;
  50612. }());
  50613. BABYLON.DepthRenderer = DepthRenderer;
  50614. })(BABYLON || (BABYLON = {}));
  50615. //# sourceMappingURL=babylon.depthRenderer.js.map
  50616. var BABYLON;
  50617. (function (BABYLON) {
  50618. var SSAORenderingPipeline = (function (_super) {
  50619. __extends(SSAORenderingPipeline, _super);
  50620. /**
  50621. * @constructor
  50622. * @param {string} name - The rendering pipeline name
  50623. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50624. * @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 }
  50625. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50626. */
  50627. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  50628. var _this = _super.call(this, scene.getEngine(), name) || this;
  50629. // Members
  50630. /**
  50631. * The PassPostProcess id in the pipeline that contains the original scene color
  50632. * @type {string}
  50633. */
  50634. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  50635. /**
  50636. * The SSAO PostProcess id in the pipeline
  50637. * @type {string}
  50638. */
  50639. _this.SSAORenderEffect = "SSAORenderEffect";
  50640. /**
  50641. * The horizontal blur PostProcess id in the pipeline
  50642. * @type {string}
  50643. */
  50644. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  50645. /**
  50646. * The vertical blur PostProcess id in the pipeline
  50647. * @type {string}
  50648. */
  50649. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  50650. /**
  50651. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  50652. * @type {string}
  50653. */
  50654. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  50655. /**
  50656. * The output strength of the SSAO post-process. Default value is 1.0.
  50657. * @type {number}
  50658. */
  50659. _this.totalStrength = 1.0;
  50660. /**
  50661. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  50662. * @type {number}
  50663. */
  50664. _this.radius = 0.0001;
  50665. /**
  50666. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  50667. * Must not be equal to fallOff and superior to fallOff.
  50668. * Default value is 0.975
  50669. * @type {number}
  50670. */
  50671. _this.area = 0.0075;
  50672. /**
  50673. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  50674. * Must not be equal to area and inferior to area.
  50675. * Default value is 0.0
  50676. * @type {number}
  50677. */
  50678. _this.fallOff = 0.000001;
  50679. /**
  50680. * The base color of the SSAO post-process
  50681. * The final result is "base + ssao" between [0, 1]
  50682. * @type {number}
  50683. */
  50684. _this.base = 0.5;
  50685. _this._firstUpdate = true;
  50686. _this._scene = scene;
  50687. // Set up assets
  50688. _this._createRandomTexture();
  50689. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  50690. var ssaoRatio = ratio.ssaoRatio || ratio;
  50691. var combineRatio = ratio.combineRatio || ratio;
  50692. _this._ratio = {
  50693. ssaoRatio: ssaoRatio,
  50694. combineRatio: combineRatio
  50695. };
  50696. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  50697. _this._createSSAOPostProcess(ssaoRatio);
  50698. _this._createBlurPostProcess(ssaoRatio);
  50699. _this._createSSAOCombinePostProcess(combineRatio);
  50700. // Set up pipeline
  50701. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  50702. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  50703. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  50704. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  50705. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  50706. // Finish
  50707. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50708. if (cameras)
  50709. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50710. return _this;
  50711. }
  50712. // Public Methods
  50713. /**
  50714. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  50715. */
  50716. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  50717. if (disableDepthRender === void 0) { disableDepthRender = false; }
  50718. for (var i = 0; i < this._scene.cameras.length; i++) {
  50719. var camera = this._scene.cameras[i];
  50720. this._originalColorPostProcess.dispose(camera);
  50721. this._ssaoPostProcess.dispose(camera);
  50722. this._blurHPostProcess.dispose(camera);
  50723. this._blurVPostProcess.dispose(camera);
  50724. this._ssaoCombinePostProcess.dispose(camera);
  50725. }
  50726. this._randomTexture.dispose();
  50727. if (disableDepthRender)
  50728. this._scene.disableDepthRenderer();
  50729. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50730. _super.prototype.dispose.call(this);
  50731. };
  50732. // Private Methods
  50733. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  50734. var _this = this;
  50735. /*
  50736. var samplerOffsets = [
  50737. -8.0, -6.0, -4.0, -2.0,
  50738. 0.0,
  50739. 2.0, 4.0, 6.0, 8.0
  50740. ];
  50741. */
  50742. var samples = 16;
  50743. var samplerOffsets = [];
  50744. for (var i = -8; i < 8; i++) {
  50745. samplerOffsets.push(i * 2);
  50746. }
  50747. 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");
  50748. this._blurHPostProcess.onApply = function (effect) {
  50749. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  50750. effect.setTexture("depthSampler", _this._depthTexture);
  50751. if (_this._firstUpdate) {
  50752. effect.setArray("samplerOffsets", samplerOffsets);
  50753. }
  50754. };
  50755. 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");
  50756. this._blurVPostProcess.onApply = function (effect) {
  50757. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  50758. effect.setTexture("depthSampler", _this._depthTexture);
  50759. if (_this._firstUpdate) {
  50760. effect.setArray("samplerOffsets", samplerOffsets);
  50761. _this._firstUpdate = false;
  50762. }
  50763. };
  50764. };
  50765. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  50766. var _this = this;
  50767. var numSamples = 16;
  50768. var sampleSphere = [
  50769. 0.5381, 0.1856, -0.4319,
  50770. 0.1379, 0.2486, 0.4430,
  50771. 0.3371, 0.5679, -0.0057,
  50772. -0.6999, -0.0451, -0.0019,
  50773. 0.0689, -0.1598, -0.8547,
  50774. 0.0560, 0.0069, -0.1843,
  50775. -0.0146, 0.1402, 0.0762,
  50776. 0.0100, -0.1924, -0.0344,
  50777. -0.3577, -0.5301, -0.4358,
  50778. -0.3169, 0.1063, 0.0158,
  50779. 0.0103, -0.5869, 0.0046,
  50780. -0.0897, -0.4940, 0.3287,
  50781. 0.7119, -0.0154, -0.0918,
  50782. -0.0533, 0.0596, -0.5411,
  50783. 0.0352, -0.0631, 0.5460,
  50784. -0.4776, 0.2847, -0.0271
  50785. ];
  50786. var samplesFactor = 1.0 / numSamples;
  50787. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  50788. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  50789. "area", "fallOff", "base", "range", "viewport"
  50790. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  50791. var viewport = new BABYLON.Vector2(0, 0);
  50792. this._ssaoPostProcess.onApply = function (effect) {
  50793. if (_this._firstUpdate) {
  50794. effect.setArray3("sampleSphere", sampleSphere);
  50795. effect.setFloat("samplesFactor", samplesFactor);
  50796. effect.setFloat("randTextureTiles", 4.0);
  50797. }
  50798. effect.setFloat("totalStrength", _this.totalStrength);
  50799. effect.setFloat("radius", _this.radius);
  50800. effect.setFloat("area", _this.area);
  50801. effect.setFloat("fallOff", _this.fallOff);
  50802. effect.setFloat("base", _this.base);
  50803. effect.setTexture("textureSampler", _this._depthTexture);
  50804. effect.setTexture("randomSampler", _this._randomTexture);
  50805. };
  50806. };
  50807. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  50808. var _this = this;
  50809. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50810. this._ssaoCombinePostProcess.onApply = function (effect) {
  50811. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  50812. };
  50813. };
  50814. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  50815. var size = 512;
  50816. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  50817. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50818. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50819. var context = this._randomTexture.getContext();
  50820. var rand = function (min, max) {
  50821. return Math.random() * (max - min) + min;
  50822. };
  50823. var randVector = BABYLON.Vector3.Zero();
  50824. for (var x = 0; x < size; x++) {
  50825. for (var y = 0; y < size; y++) {
  50826. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  50827. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  50828. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  50829. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  50830. context.fillRect(x, y, 1, 1);
  50831. }
  50832. }
  50833. this._randomTexture.update(false);
  50834. };
  50835. return SSAORenderingPipeline;
  50836. }(BABYLON.PostProcessRenderPipeline));
  50837. __decorate([
  50838. BABYLON.serialize()
  50839. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  50840. __decorate([
  50841. BABYLON.serialize()
  50842. ], SSAORenderingPipeline.prototype, "radius", void 0);
  50843. __decorate([
  50844. BABYLON.serialize()
  50845. ], SSAORenderingPipeline.prototype, "area", void 0);
  50846. __decorate([
  50847. BABYLON.serialize()
  50848. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  50849. __decorate([
  50850. BABYLON.serialize()
  50851. ], SSAORenderingPipeline.prototype, "base", void 0);
  50852. __decorate([
  50853. BABYLON.serialize()
  50854. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  50855. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  50856. })(BABYLON || (BABYLON = {}));
  50857. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  50858. var BABYLON;
  50859. (function (BABYLON) {
  50860. var SSAO2RenderingPipeline = (function (_super) {
  50861. __extends(SSAO2RenderingPipeline, _super);
  50862. /**
  50863. * @constructor
  50864. * @param {string} name - The rendering pipeline name
  50865. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50866. * @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 }
  50867. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50868. */
  50869. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  50870. var _this = _super.call(this, scene.getEngine(), name) || this;
  50871. // Members
  50872. /**
  50873. * The PassPostProcess id in the pipeline that contains the original scene color
  50874. * @type {string}
  50875. */
  50876. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  50877. /**
  50878. * The SSAO PostProcess id in the pipeline
  50879. * @type {string}
  50880. */
  50881. _this.SSAORenderEffect = "SSAORenderEffect";
  50882. /**
  50883. * The horizontal blur PostProcess id in the pipeline
  50884. * @type {string}
  50885. */
  50886. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  50887. /**
  50888. * The vertical blur PostProcess id in the pipeline
  50889. * @type {string}
  50890. */
  50891. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  50892. /**
  50893. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  50894. * @type {string}
  50895. */
  50896. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  50897. /**
  50898. * The output strength of the SSAO post-process. Default value is 1.0.
  50899. * @type {number}
  50900. */
  50901. _this.totalStrength = 1.0;
  50902. /**
  50903. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  50904. * @type {number}
  50905. */
  50906. _this.maxZ = 100.0;
  50907. /**
  50908. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  50909. * @type {number}
  50910. */
  50911. _this.minZAspect = 0.2;
  50912. /**
  50913. * Number of samples used for the SSAO calculations. Default value is 8
  50914. * @type {number}
  50915. */
  50916. _this._samples = 8;
  50917. /**
  50918. * Are we using bilateral blur ?
  50919. * @type {boolean}
  50920. */
  50921. _this._expensiveBlur = true;
  50922. /**
  50923. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  50924. * @type {number}
  50925. */
  50926. _this.radius = 2.0;
  50927. /**
  50928. * The base color of the SSAO post-process
  50929. * The final result is "base + ssao" between [0, 1]
  50930. * @type {number}
  50931. */
  50932. _this.base = 0.1;
  50933. _this._firstUpdate = true;
  50934. _this._scene = scene;
  50935. if (!_this.isSupported) {
  50936. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  50937. return _this;
  50938. }
  50939. var ssaoRatio = ratio.ssaoRatio || ratio;
  50940. var blurRatio = ratio.blurRatio || ratio;
  50941. _this._ratio = {
  50942. ssaoRatio: ssaoRatio,
  50943. blurRatio: blurRatio
  50944. };
  50945. // Set up assets
  50946. _this._createRandomTexture();
  50947. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  50948. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  50949. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  50950. _this._createSSAOPostProcess(1.0);
  50951. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  50952. _this._createSSAOCombinePostProcess(blurRatio);
  50953. // Set up pipeline
  50954. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  50955. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  50956. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  50957. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  50958. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  50959. // Finish
  50960. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50961. if (cameras)
  50962. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50963. return _this;
  50964. }
  50965. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  50966. get: function () {
  50967. return this._samples;
  50968. },
  50969. set: function (n) {
  50970. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  50971. this._samples = n;
  50972. this._sampleSphere = this._generateHemisphere();
  50973. this._firstUpdate = true;
  50974. },
  50975. enumerable: true,
  50976. configurable: true
  50977. });
  50978. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  50979. get: function () {
  50980. return this._expensiveBlur;
  50981. },
  50982. set: function (b) {
  50983. 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"]);
  50984. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  50985. this._expensiveBlur = b;
  50986. this._firstUpdate = true;
  50987. },
  50988. enumerable: true,
  50989. configurable: true
  50990. });
  50991. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  50992. /**
  50993. * Support test.
  50994. * @type {boolean}
  50995. */
  50996. get: function () {
  50997. var engine = BABYLON.Engine.LastCreatedEngine;
  50998. return engine.webGLVersion > 1;
  50999. },
  51000. enumerable: true,
  51001. configurable: true
  51002. });
  51003. // Public Methods
  51004. /**
  51005. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  51006. */
  51007. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  51008. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  51009. for (var i = 0; i < this._scene.cameras.length; i++) {
  51010. var camera = this._scene.cameras[i];
  51011. this._originalColorPostProcess.dispose(camera);
  51012. this._ssaoPostProcess.dispose(camera);
  51013. this._blurHPostProcess.dispose(camera);
  51014. this._blurVPostProcess.dispose(camera);
  51015. this._ssaoCombinePostProcess.dispose(camera);
  51016. }
  51017. this._randomTexture.dispose();
  51018. if (disableGeometryBufferRenderer)
  51019. this._scene.disableGeometryBufferRenderer();
  51020. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51021. _super.prototype.dispose.call(this);
  51022. };
  51023. // Private Methods
  51024. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  51025. var _this = this;
  51026. var samples = 16;
  51027. this._samplerOffsets = [];
  51028. var expensive = this.expensiveBlur;
  51029. for (var i = -8; i < 8; i++) {
  51030. this._samplerOffsets.push(i * 2 + 0.5);
  51031. }
  51032. 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");
  51033. this._blurHPostProcess.onApply = function (effect) {
  51034. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  51035. effect.setFloat("near", _this._scene.activeCamera.minZ);
  51036. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  51037. effect.setFloat("radius", _this.radius);
  51038. effect.setTexture("depthSampler", _this._depthTexture);
  51039. if (_this._firstUpdate) {
  51040. effect.setArray("samplerOffsets", _this._samplerOffsets);
  51041. }
  51042. };
  51043. 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");
  51044. this._blurVPostProcess.onApply = function (effect) {
  51045. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  51046. effect.setFloat("near", _this._scene.activeCamera.minZ);
  51047. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  51048. effect.setFloat("radius", _this.radius);
  51049. effect.setTexture("depthSampler", _this._depthTexture);
  51050. if (_this._firstUpdate) {
  51051. effect.setArray("samplerOffsets", _this._samplerOffsets);
  51052. _this._firstUpdate = false;
  51053. }
  51054. };
  51055. };
  51056. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  51057. var numSamples = this.samples;
  51058. var result = [];
  51059. var vector, scale;
  51060. var rand = function (min, max) {
  51061. return Math.random() * (max - min) + min;
  51062. };
  51063. var lerp = function (start, end, percent) {
  51064. return (start + percent * (end - start));
  51065. };
  51066. var i = 0;
  51067. var normal = new BABYLON.Vector3(0, 0, 1);
  51068. while (i < numSamples) {
  51069. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  51070. vector.normalize();
  51071. scale = i / numSamples;
  51072. scale = lerp(0.1, 1.0, scale * scale);
  51073. vector.scaleInPlace(scale);
  51074. result.push(vector.x, vector.y, vector.z);
  51075. i++;
  51076. }
  51077. return result;
  51078. };
  51079. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  51080. var _this = this;
  51081. var numSamples = this.samples;
  51082. this._sampleSphere = this._generateHemisphere();
  51083. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  51084. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  51085. "base", "range", "projection", "near", "far", "texelSize",
  51086. "xViewport", "yViewport", "maxZ", "minZAspect"
  51087. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  51088. this._ssaoPostProcess.onApply = function (effect) {
  51089. if (_this._firstUpdate) {
  51090. effect.setArray3("sampleSphere", _this._sampleSphere);
  51091. effect.setFloat("randTextureTiles", 4.0);
  51092. }
  51093. effect.setFloat("samplesFactor", 1 / _this.samples);
  51094. effect.setFloat("totalStrength", _this.totalStrength);
  51095. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  51096. effect.setFloat("radius", _this.radius);
  51097. effect.setFloat("maxZ", _this.maxZ);
  51098. effect.setFloat("minZAspect", _this.minZAspect);
  51099. effect.setFloat("base", _this.base);
  51100. effect.setFloat("near", _this._scene.activeCamera.minZ);
  51101. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  51102. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  51103. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  51104. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  51105. effect.setTexture("textureSampler", _this._depthTexture);
  51106. effect.setTexture("normalSampler", _this._normalTexture);
  51107. effect.setTexture("randomSampler", _this._randomTexture);
  51108. };
  51109. };
  51110. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  51111. var _this = this;
  51112. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51113. this._ssaoCombinePostProcess.onApply = function (effect) {
  51114. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  51115. };
  51116. };
  51117. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  51118. var size = 512;
  51119. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51120. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51121. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51122. var context = this._randomTexture.getContext();
  51123. var rand = function (min, max) {
  51124. return Math.random() * (max - min) + min;
  51125. };
  51126. var randVector = BABYLON.Vector3.Zero();
  51127. for (var x = 0; x < size; x++) {
  51128. for (var y = 0; y < size; y++) {
  51129. randVector.x = rand(0.0, 1.0);
  51130. randVector.y = rand(0.0, 1.0);
  51131. randVector.z = 0.0;
  51132. randVector.normalize();
  51133. randVector.scaleInPlace(255);
  51134. randVector.x = Math.floor(randVector.x);
  51135. randVector.y = Math.floor(randVector.y);
  51136. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  51137. context.fillRect(x, y, 1, 1);
  51138. }
  51139. }
  51140. this._randomTexture.update(false);
  51141. };
  51142. return SSAO2RenderingPipeline;
  51143. }(BABYLON.PostProcessRenderPipeline));
  51144. __decorate([
  51145. BABYLON.serialize()
  51146. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  51147. __decorate([
  51148. BABYLON.serialize()
  51149. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  51150. __decorate([
  51151. BABYLON.serialize()
  51152. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  51153. __decorate([
  51154. BABYLON.serialize("samples")
  51155. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  51156. __decorate([
  51157. BABYLON.serialize("expensiveBlur")
  51158. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  51159. __decorate([
  51160. BABYLON.serialize()
  51161. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  51162. __decorate([
  51163. BABYLON.serialize()
  51164. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  51165. __decorate([
  51166. BABYLON.serialize()
  51167. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  51168. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  51169. })(BABYLON || (BABYLON = {}));
  51170. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  51171. // BABYLON.JS Chromatic Aberration GLSL Shader
  51172. // Author: Olivier Guyot
  51173. // Separates very slightly R, G and B colors on the edges of the screen
  51174. // Inspired by Francois Tarlier & Martins Upitis
  51175. var BABYLON;
  51176. (function (BABYLON) {
  51177. var LensRenderingPipeline = (function (_super) {
  51178. __extends(LensRenderingPipeline, _super);
  51179. /**
  51180. * @constructor
  51181. *
  51182. * Effect parameters are as follow:
  51183. * {
  51184. * chromatic_aberration: number; // from 0 to x (1 for realism)
  51185. * edge_blur: number; // from 0 to x (1 for realism)
  51186. * distortion: number; // from 0 to x (1 for realism)
  51187. * grain_amount: number; // from 0 to 1
  51188. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  51189. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  51190. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  51191. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  51192. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  51193. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  51194. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  51195. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  51196. * }
  51197. * Note: if an effect parameter is unset, effect is disabled
  51198. *
  51199. * @param {string} name - The rendering pipeline name
  51200. * @param {object} parameters - An object containing all parameters (see above)
  51201. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51202. * @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)
  51203. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51204. */
  51205. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  51206. if (ratio === void 0) { ratio = 1.0; }
  51207. var _this = _super.call(this, scene.getEngine(), name) || this;
  51208. // Lens effects can be of the following:
  51209. // - chromatic aberration (slight shift of RGB colors)
  51210. // - blur on the edge of the lens
  51211. // - lens distortion
  51212. // - depth-of-field blur & highlights enhancing
  51213. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  51214. // - grain effect (noise or custom texture)
  51215. // Two additional texture samplers are needed:
  51216. // - depth map (for depth-of-field)
  51217. // - grain texture
  51218. /**
  51219. * The chromatic aberration PostProcess id in the pipeline
  51220. * @type {string}
  51221. */
  51222. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  51223. /**
  51224. * The highlights enhancing PostProcess id in the pipeline
  51225. * @type {string}
  51226. */
  51227. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  51228. /**
  51229. * The depth-of-field PostProcess id in the pipeline
  51230. * @type {string}
  51231. */
  51232. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  51233. _this._scene = scene;
  51234. // Fetch texture samplers
  51235. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  51236. if (parameters.grain_texture) {
  51237. _this._grainTexture = parameters.grain_texture;
  51238. }
  51239. else {
  51240. _this._createGrainTexture();
  51241. }
  51242. // save parameters
  51243. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  51244. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  51245. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  51246. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  51247. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  51248. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  51249. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  51250. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  51251. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  51252. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  51253. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  51254. // Create effects
  51255. _this._createChromaticAberrationPostProcess(ratio);
  51256. _this._createHighlightsPostProcess(ratio);
  51257. _this._createDepthOfFieldPostProcess(ratio / 4);
  51258. // Set up pipeline
  51259. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  51260. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  51261. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  51262. if (_this._highlightsGain === -1) {
  51263. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  51264. }
  51265. // Finish
  51266. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51267. if (cameras) {
  51268. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51269. }
  51270. return _this;
  51271. }
  51272. // public methods (self explanatory)
  51273. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  51274. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  51275. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  51276. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  51277. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  51278. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  51279. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  51280. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  51281. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  51282. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  51283. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  51284. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  51285. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  51286. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  51287. };
  51288. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  51289. this._highlightsPostProcess.updateEffect();
  51290. };
  51291. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  51292. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  51293. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  51294. this._highlightsGain = amount;
  51295. };
  51296. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  51297. if (this._highlightsGain === -1) {
  51298. this._highlightsGain = 1.0;
  51299. }
  51300. this._highlightsThreshold = amount;
  51301. };
  51302. LensRenderingPipeline.prototype.disableHighlights = function () {
  51303. this._highlightsGain = -1;
  51304. };
  51305. /**
  51306. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  51307. */
  51308. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  51309. if (disableDepthRender === void 0) { disableDepthRender = false; }
  51310. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51311. this._chromaticAberrationPostProcess = undefined;
  51312. this._highlightsPostProcess = undefined;
  51313. this._depthOfFieldPostProcess = undefined;
  51314. this._grainTexture.dispose();
  51315. if (disableDepthRender)
  51316. this._scene.disableDepthRenderer();
  51317. };
  51318. // colors shifting and distortion
  51319. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  51320. var _this = this;
  51321. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  51322. [], // samplers
  51323. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51324. this._chromaticAberrationPostProcess.onApply = function (effect) {
  51325. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  51326. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51327. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51328. };
  51329. };
  51330. // highlights enhancing
  51331. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  51332. var _this = this;
  51333. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  51334. [], // samplers
  51335. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  51336. this._highlightsPostProcess.onApply = function (effect) {
  51337. effect.setFloat('gain', _this._highlightsGain);
  51338. effect.setFloat('threshold', _this._highlightsThreshold);
  51339. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  51340. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51341. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51342. };
  51343. };
  51344. // colors shifting and distortion
  51345. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  51346. var _this = this;
  51347. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  51348. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  51349. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  51350. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51351. this._depthOfFieldPostProcess.onApply = function (effect) {
  51352. effect.setTexture("depthSampler", _this._depthTexture);
  51353. effect.setTexture("grainSampler", _this._grainTexture);
  51354. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  51355. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  51356. effect.setFloat('grain_amount', _this._grainAmount);
  51357. effect.setBool('blur_noise', _this._blurNoise);
  51358. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51359. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51360. effect.setFloat('distortion', _this._distortion);
  51361. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  51362. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  51363. effect.setFloat('aperture', _this._dofAperture);
  51364. effect.setFloat('darken', _this._dofDarken);
  51365. effect.setFloat('edge_blur', _this._edgeBlur);
  51366. effect.setBool('highlights', (_this._highlightsGain !== -1));
  51367. effect.setFloat('near', _this._scene.activeCamera.minZ);
  51368. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  51369. };
  51370. };
  51371. // creates a black and white random noise texture, 512x512
  51372. LensRenderingPipeline.prototype._createGrainTexture = function () {
  51373. var size = 512;
  51374. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51375. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51376. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51377. var context = this._grainTexture.getContext();
  51378. var rand = function (min, max) {
  51379. return Math.random() * (max - min) + min;
  51380. };
  51381. var value;
  51382. for (var x = 0; x < size; x++) {
  51383. for (var y = 0; y < size; y++) {
  51384. value = Math.floor(rand(0.42, 0.58) * 255);
  51385. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  51386. context.fillRect(x, y, 1, 1);
  51387. }
  51388. }
  51389. this._grainTexture.update(false);
  51390. };
  51391. return LensRenderingPipeline;
  51392. }(BABYLON.PostProcessRenderPipeline));
  51393. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  51394. })(BABYLON || (BABYLON = {}));
  51395. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  51396. var BABYLON;
  51397. (function (BABYLON) {
  51398. var StandardRenderingPipeline = (function (_super) {
  51399. __extends(StandardRenderingPipeline, _super);
  51400. /**
  51401. * @constructor
  51402. * @param {string} name - The rendering pipeline name
  51403. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51404. * @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)
  51405. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  51406. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51407. */
  51408. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  51409. if (originalPostProcess === void 0) { originalPostProcess = null; }
  51410. var _this = _super.call(this, scene.getEngine(), name) || this;
  51411. _this.downSampleX4PostProcess = null;
  51412. _this.brightPassPostProcess = null;
  51413. _this.blurHPostProcesses = [];
  51414. _this.blurVPostProcesses = [];
  51415. _this.textureAdderPostProcess = null;
  51416. _this.volumetricLightPostProcess = null;
  51417. _this.volumetricLightSmoothXPostProcess = null;
  51418. _this.volumetricLightSmoothYPostProcess = null;
  51419. _this.volumetricLightMergePostProces = null;
  51420. _this.volumetricLightFinalPostProcess = null;
  51421. _this.luminancePostProcess = null;
  51422. _this.luminanceDownSamplePostProcesses = [];
  51423. _this.hdrPostProcess = null;
  51424. _this.textureAdderFinalPostProcess = null;
  51425. _this.lensFlareFinalPostProcess = null;
  51426. _this.hdrFinalPostProcess = null;
  51427. _this.lensFlarePostProcess = null;
  51428. _this.lensFlareComposePostProcess = null;
  51429. _this.motionBlurPostProcess = null;
  51430. _this.depthOfFieldPostProcess = null;
  51431. // Values
  51432. _this.brightThreshold = 1.0;
  51433. _this.blurWidth = 512.0;
  51434. _this.horizontalBlur = false;
  51435. _this.exposure = 1.0;
  51436. _this.lensTexture = null;
  51437. _this.volumetricLightCoefficient = 0.2;
  51438. _this.volumetricLightPower = 4.0;
  51439. _this.volumetricLightBlurScale = 64.0;
  51440. _this.sourceLight = null;
  51441. _this.hdrMinimumLuminance = 1.0;
  51442. _this.hdrDecreaseRate = 0.5;
  51443. _this.hdrIncreaseRate = 0.5;
  51444. _this.lensColorTexture = null;
  51445. _this.lensFlareStrength = 20.0;
  51446. _this.lensFlareGhostDispersal = 1.4;
  51447. _this.lensFlareHaloWidth = 0.7;
  51448. _this.lensFlareDistortionStrength = 16.0;
  51449. _this.lensStarTexture = null;
  51450. _this.lensFlareDirtTexture = null;
  51451. _this.depthOfFieldDistance = 10.0;
  51452. _this.depthOfFieldBlurWidth = 64.0;
  51453. _this.motionStrength = 1.0;
  51454. // IAnimatable
  51455. _this.animations = [];
  51456. _this._currentDepthOfFieldSource = null;
  51457. _this._hdrCurrentLuminance = 1.0;
  51458. // Getters and setters
  51459. _this._bloomEnabled = true;
  51460. _this._depthOfFieldEnabled = false;
  51461. _this._vlsEnabled = false;
  51462. _this._lensFlareEnabled = false;
  51463. _this._hdrEnabled = false;
  51464. _this._motionBlurEnabled = false;
  51465. _this._motionBlurSamples = 64.0;
  51466. _this._volumetricLightStepsCount = 50.0;
  51467. _this._cameras = cameras || [];
  51468. // Initialize
  51469. _this._scene = scene;
  51470. _this._basePostProcess = originalPostProcess;
  51471. _this._ratio = ratio;
  51472. // Misc
  51473. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51474. // Finish
  51475. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51476. _this._buildPipeline();
  51477. return _this;
  51478. }
  51479. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  51480. get: function () {
  51481. return this._bloomEnabled;
  51482. },
  51483. set: function (enabled) {
  51484. if (this._bloomEnabled === enabled) {
  51485. return;
  51486. }
  51487. this._bloomEnabled = enabled;
  51488. this._buildPipeline();
  51489. },
  51490. enumerable: true,
  51491. configurable: true
  51492. });
  51493. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  51494. get: function () {
  51495. return this._depthOfFieldEnabled;
  51496. },
  51497. set: function (enabled) {
  51498. if (this._depthOfFieldEnabled === enabled) {
  51499. return;
  51500. }
  51501. this._depthOfFieldEnabled = enabled;
  51502. this._buildPipeline();
  51503. },
  51504. enumerable: true,
  51505. configurable: true
  51506. });
  51507. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  51508. get: function () {
  51509. return this._lensFlareEnabled;
  51510. },
  51511. set: function (enabled) {
  51512. if (this._lensFlareEnabled === enabled) {
  51513. return;
  51514. }
  51515. this._lensFlareEnabled = enabled;
  51516. this._buildPipeline();
  51517. },
  51518. enumerable: true,
  51519. configurable: true
  51520. });
  51521. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  51522. get: function () {
  51523. return this._hdrEnabled;
  51524. },
  51525. set: function (enabled) {
  51526. if (this._hdrEnabled === enabled) {
  51527. return;
  51528. }
  51529. this._hdrEnabled = enabled;
  51530. this._buildPipeline();
  51531. },
  51532. enumerable: true,
  51533. configurable: true
  51534. });
  51535. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  51536. get: function () {
  51537. return this._vlsEnabled;
  51538. },
  51539. set: function (enabled) {
  51540. if (this._vlsEnabled === enabled) {
  51541. return;
  51542. }
  51543. if (enabled) {
  51544. var geometry = this._scene.enableGeometryBufferRenderer();
  51545. if (!geometry) {
  51546. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  51547. return;
  51548. }
  51549. }
  51550. this._vlsEnabled = enabled;
  51551. this._buildPipeline();
  51552. },
  51553. enumerable: true,
  51554. configurable: true
  51555. });
  51556. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  51557. get: function () {
  51558. return this._motionBlurEnabled;
  51559. },
  51560. set: function (enabled) {
  51561. if (this._motionBlurEnabled === enabled) {
  51562. return;
  51563. }
  51564. this._motionBlurEnabled = enabled;
  51565. this._buildPipeline();
  51566. },
  51567. enumerable: true,
  51568. configurable: true
  51569. });
  51570. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  51571. get: function () {
  51572. return this._volumetricLightStepsCount;
  51573. },
  51574. set: function (count) {
  51575. if (this.volumetricLightPostProcess) {
  51576. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  51577. }
  51578. this._volumetricLightStepsCount = count;
  51579. },
  51580. enumerable: true,
  51581. configurable: true
  51582. });
  51583. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  51584. get: function () {
  51585. return this._motionBlurSamples;
  51586. },
  51587. set: function (samples) {
  51588. if (this.motionBlurPostProcess) {
  51589. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  51590. }
  51591. this._motionBlurSamples = samples;
  51592. },
  51593. enumerable: true,
  51594. configurable: true
  51595. });
  51596. StandardRenderingPipeline.prototype._buildPipeline = function () {
  51597. var _this = this;
  51598. var ratio = this._ratio;
  51599. var scene = this._scene;
  51600. this._disposePostProcesses();
  51601. this._reset();
  51602. // Create pass post-process
  51603. if (!this._basePostProcess) {
  51604. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  51605. this.originalPostProcess.onApply = function (effect) {
  51606. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  51607. };
  51608. }
  51609. else {
  51610. this.originalPostProcess = this._basePostProcess;
  51611. }
  51612. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  51613. this._currentDepthOfFieldSource = this.originalPostProcess;
  51614. if (this._vlsEnabled) {
  51615. // Create volumetric light
  51616. this._createVolumetricLightPostProcess(scene, ratio);
  51617. // Create volumetric light final post-process
  51618. 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);
  51619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  51620. }
  51621. if (this._bloomEnabled) {
  51622. // Create down sample X4 post-process
  51623. this._createDownSampleX4PostProcess(scene, ratio / 2);
  51624. // Create bright pass post-process
  51625. this._createBrightPassPostProcess(scene, ratio / 2);
  51626. // Create gaussian blur post-processes (down sampling blurs)
  51627. this._createBlurPostProcesses(scene, ratio / 4, 1);
  51628. // Create texture adder post-process
  51629. this._createTextureAdderPostProcess(scene, ratio);
  51630. // Create depth-of-field source post-process
  51631. 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);
  51632. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  51633. }
  51634. if (this._lensFlareEnabled) {
  51635. // Create lens flare post-process
  51636. this._createLensFlarePostProcess(scene, ratio);
  51637. // Create depth-of-field source post-process post lens-flare and disable it now
  51638. 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);
  51639. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  51640. }
  51641. if (this._hdrEnabled) {
  51642. // Create luminance
  51643. this._createLuminancePostProcesses(scene, this._floatTextureType);
  51644. // Create HDR
  51645. this._createHdrPostProcess(scene, ratio);
  51646. // Create depth-of-field source post-process post hdr and disable it now
  51647. 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);
  51648. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  51649. }
  51650. if (this._depthOfFieldEnabled) {
  51651. // Create gaussian blur used by depth-of-field
  51652. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  51653. // Create depth-of-field post-process
  51654. this._createDepthOfFieldPostProcess(scene, ratio);
  51655. }
  51656. if (this._motionBlurEnabled) {
  51657. // Create motion blur post-process
  51658. this._createMotionBlurPostProcess(scene, ratio);
  51659. }
  51660. if (this._cameras !== null) {
  51661. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  51662. }
  51663. };
  51664. // Down Sample X4 Post-Processs
  51665. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  51666. var _this = this;
  51667. var downSampleX4Offsets = new Array(32);
  51668. 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);
  51669. this.downSampleX4PostProcess.onApply = function (effect) {
  51670. var id = 0;
  51671. for (var i = -2; i < 2; i++) {
  51672. for (var j = -2; j < 2; j++) {
  51673. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  51674. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  51675. id += 2;
  51676. }
  51677. }
  51678. effect.setArray2("dsOffsets", downSampleX4Offsets);
  51679. };
  51680. // Add to pipeline
  51681. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  51682. };
  51683. // Brightpass Post-Process
  51684. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  51685. var _this = this;
  51686. var brightOffsets = new Array(8);
  51687. 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);
  51688. this.brightPassPostProcess.onApply = function (effect) {
  51689. var sU = (1.0 / _this.brightPassPostProcess.width);
  51690. var sV = (1.0 / _this.brightPassPostProcess.height);
  51691. brightOffsets[0] = -0.5 * sU;
  51692. brightOffsets[1] = 0.5 * sV;
  51693. brightOffsets[2] = 0.5 * sU;
  51694. brightOffsets[3] = 0.5 * sV;
  51695. brightOffsets[4] = -0.5 * sU;
  51696. brightOffsets[5] = -0.5 * sV;
  51697. brightOffsets[6] = 0.5 * sU;
  51698. brightOffsets[7] = -0.5 * sV;
  51699. effect.setArray2("dsOffsets", brightOffsets);
  51700. effect.setFloat("brightThreshold", _this.brightThreshold);
  51701. };
  51702. // Add to pipeline
  51703. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  51704. };
  51705. // Create blur H&V post-processes
  51706. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  51707. var _this = this;
  51708. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  51709. var engine = scene.getEngine();
  51710. 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);
  51711. 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);
  51712. blurX.onActivateObservable.add(function () {
  51713. var dw = blurX.width / engine.getRenderingCanvas().width;
  51714. blurX.kernel = _this[blurWidthKey] * dw;
  51715. });
  51716. blurY.onActivateObservable.add(function () {
  51717. var dw = blurY.height / engine.getRenderingCanvas().height;
  51718. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  51719. });
  51720. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  51721. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  51722. this.blurHPostProcesses.push(blurX);
  51723. this.blurVPostProcesses.push(blurY);
  51724. };
  51725. // Create texture adder post-process
  51726. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  51727. var _this = this;
  51728. 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);
  51729. this.textureAdderPostProcess.onApply = function (effect) {
  51730. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  51731. effect.setTexture("lensSampler", _this.lensTexture);
  51732. effect.setFloat("exposure", _this.exposure);
  51733. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  51734. };
  51735. // Add to pipeline
  51736. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  51737. };
  51738. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  51739. var _this = this;
  51740. var geometryRenderer = scene.enableGeometryBufferRenderer();
  51741. geometryRenderer.enablePosition = true;
  51742. var geometry = geometryRenderer.getGBuffer();
  51743. // Base post-process
  51744. 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));
  51745. var depthValues = BABYLON.Vector2.Zero();
  51746. this.volumetricLightPostProcess.onApply = function (effect) {
  51747. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  51748. var generator = _this.sourceLight.getShadowGenerator();
  51749. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  51750. effect.setTexture("positionSampler", geometry.textures[2]);
  51751. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  51752. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  51753. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  51754. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  51755. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  51756. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  51757. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  51758. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  51759. effect.setVector2("depthValues", depthValues);
  51760. }
  51761. };
  51762. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  51763. // Smooth
  51764. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  51765. // Merge
  51766. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  51767. this.volumetricLightMergePostProces.onApply = function (effect) {
  51768. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  51769. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  51770. };
  51771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  51772. };
  51773. // Create luminance
  51774. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  51775. var _this = this;
  51776. // Create luminance
  51777. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  51778. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  51779. var offsets = [];
  51780. this.luminancePostProcess.onApply = function (effect) {
  51781. var sU = (1.0 / _this.luminancePostProcess.width);
  51782. var sV = (1.0 / _this.luminancePostProcess.height);
  51783. offsets[0] = -0.5 * sU;
  51784. offsets[1] = 0.5 * sV;
  51785. offsets[2] = 0.5 * sU;
  51786. offsets[3] = 0.5 * sV;
  51787. offsets[4] = -0.5 * sU;
  51788. offsets[5] = -0.5 * sV;
  51789. offsets[6] = 0.5 * sU;
  51790. offsets[7] = -0.5 * sV;
  51791. effect.setArray2("lumOffsets", offsets);
  51792. };
  51793. // Add to pipeline
  51794. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  51795. // Create down sample luminance
  51796. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  51797. var size = Math.pow(3, i);
  51798. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  51799. if (i === 0) {
  51800. defines += "#define FINAL_DOWN_SAMPLER";
  51801. }
  51802. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  51803. this.luminanceDownSamplePostProcesses.push(postProcess);
  51804. }
  51805. // Create callbacks and add effects
  51806. var lastLuminance = this.luminancePostProcess;
  51807. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  51808. var downSampleOffsets = new Array(18);
  51809. pp.onApply = function (effect) {
  51810. var id = 0;
  51811. for (var x = -1; x < 2; x++) {
  51812. for (var y = -1; y < 2; y++) {
  51813. downSampleOffsets[id] = x / lastLuminance.width;
  51814. downSampleOffsets[id + 1] = y / lastLuminance.height;
  51815. id += 2;
  51816. }
  51817. }
  51818. effect.setArray2("dsOffsets", downSampleOffsets);
  51819. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  51820. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  51821. lastLuminance = _this.luminancePostProcess;
  51822. }
  51823. else {
  51824. lastLuminance = pp;
  51825. }
  51826. };
  51827. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  51828. pp.onAfterRender = function (effect) {
  51829. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  51830. 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);
  51831. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  51832. };
  51833. }
  51834. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  51835. });
  51836. };
  51837. // Create HDR post-process
  51838. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  51839. var _this = this;
  51840. 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);
  51841. var outputLiminance = 1;
  51842. var time = 0;
  51843. var lastTime = 0;
  51844. this.hdrPostProcess.onApply = function (effect) {
  51845. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  51846. time += scene.getEngine().getDeltaTime();
  51847. if (outputLiminance < 0) {
  51848. outputLiminance = _this._hdrCurrentLuminance;
  51849. }
  51850. else {
  51851. var dt = (lastTime - time) / 1000.0;
  51852. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  51853. outputLiminance += _this.hdrDecreaseRate * dt;
  51854. }
  51855. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  51856. outputLiminance -= _this.hdrIncreaseRate * dt;
  51857. }
  51858. else {
  51859. outputLiminance = _this._hdrCurrentLuminance;
  51860. }
  51861. }
  51862. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  51863. effect.setFloat("averageLuminance", outputLiminance);
  51864. lastTime = time;
  51865. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  51866. };
  51867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  51868. };
  51869. // Create lens flare post-process
  51870. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  51871. var _this = this;
  51872. 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);
  51873. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  51874. this._createBlurPostProcesses(scene, ratio / 4, 2);
  51875. 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);
  51876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  51877. var resolution = new BABYLON.Vector2(0, 0);
  51878. // Lens flare
  51879. this.lensFlarePostProcess.onApply = function (effect) {
  51880. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  51881. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  51882. effect.setFloat("strength", _this.lensFlareStrength);
  51883. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  51884. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  51885. // Shift
  51886. resolution.x = _this.lensFlarePostProcess.width;
  51887. resolution.y = _this.lensFlarePostProcess.height;
  51888. effect.setVector2("resolution", resolution);
  51889. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  51890. };
  51891. // Compose
  51892. 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);
  51893. 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);
  51894. this.lensFlareComposePostProcess.onApply = function (effect) {
  51895. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  51896. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  51897. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  51898. // Lens start rotation matrix
  51899. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  51900. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  51901. 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));
  51902. camRot *= 4.0;
  51903. 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);
  51904. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  51905. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  51906. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  51907. };
  51908. };
  51909. // Create depth-of-field post-process
  51910. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  51911. var _this = this;
  51912. 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);
  51913. this.depthOfFieldPostProcess.onApply = function (effect) {
  51914. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  51915. effect.setTexture("depthSampler", _this._getDepthTexture());
  51916. effect.setFloat("distance", _this.depthOfFieldDistance);
  51917. };
  51918. // Add to pipeline
  51919. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  51920. };
  51921. // Create motion blur post-process
  51922. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  51923. var _this = this;
  51924. 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);
  51925. var motionScale = 0;
  51926. var prevViewProjection = BABYLON.Matrix.Identity();
  51927. var invViewProjection = BABYLON.Matrix.Identity();
  51928. var viewProjection = BABYLON.Matrix.Identity();
  51929. var screenSize = BABYLON.Vector2.Zero();
  51930. this.motionBlurPostProcess.onApply = function (effect) {
  51931. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  51932. viewProjection.invertToRef(invViewProjection);
  51933. effect.setMatrix("inverseViewProjection", invViewProjection);
  51934. effect.setMatrix("prevViewProjection", prevViewProjection);
  51935. prevViewProjection = viewProjection;
  51936. screenSize.x = _this.motionBlurPostProcess.width;
  51937. screenSize.y = _this.motionBlurPostProcess.height;
  51938. effect.setVector2("screenSize", screenSize);
  51939. motionScale = scene.getEngine().getFps() / 60.0;
  51940. effect.setFloat("motionScale", motionScale);
  51941. effect.setFloat("motionStrength", _this.motionStrength);
  51942. effect.setTexture("depthSampler", _this._getDepthTexture());
  51943. };
  51944. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  51945. };
  51946. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  51947. var geometry = this._scene.enableGeometryBufferRenderer();
  51948. if (geometry) {
  51949. return geometry.getGBuffer().textures[0];
  51950. }
  51951. return this._scene.enableDepthRenderer().getDepthMap();
  51952. };
  51953. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  51954. for (var i = 0; i < this._cameras.length; i++) {
  51955. var camera = this._cameras[i];
  51956. if (this.originalPostProcess) {
  51957. this.originalPostProcess.dispose(camera);
  51958. }
  51959. if (this.downSampleX4PostProcess) {
  51960. this.downSampleX4PostProcess.dispose(camera);
  51961. }
  51962. if (this.brightPassPostProcess) {
  51963. this.brightPassPostProcess.dispose(camera);
  51964. }
  51965. if (this.textureAdderPostProcess) {
  51966. this.textureAdderPostProcess.dispose(camera);
  51967. }
  51968. if (this.textureAdderFinalPostProcess) {
  51969. this.textureAdderFinalPostProcess.dispose(camera);
  51970. }
  51971. if (this.volumetricLightPostProcess) {
  51972. this.volumetricLightPostProcess.dispose(camera);
  51973. }
  51974. if (this.volumetricLightSmoothXPostProcess) {
  51975. this.volumetricLightSmoothXPostProcess.dispose(camera);
  51976. }
  51977. if (this.volumetricLightSmoothYPostProcess) {
  51978. this.volumetricLightSmoothYPostProcess.dispose(camera);
  51979. }
  51980. if (this.volumetricLightMergePostProces) {
  51981. this.volumetricLightMergePostProces.dispose(camera);
  51982. }
  51983. if (this.volumetricLightFinalPostProcess) {
  51984. this.volumetricLightFinalPostProcess.dispose(camera);
  51985. }
  51986. if (this.lensFlarePostProcess) {
  51987. this.lensFlarePostProcess.dispose(camera);
  51988. }
  51989. if (this.lensFlareComposePostProcess) {
  51990. this.lensFlareComposePostProcess.dispose(camera);
  51991. }
  51992. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  51993. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  51994. }
  51995. if (this.luminancePostProcess) {
  51996. this.luminancePostProcess.dispose(camera);
  51997. }
  51998. if (this.hdrPostProcess) {
  51999. this.hdrPostProcess.dispose(camera);
  52000. }
  52001. if (this.hdrFinalPostProcess) {
  52002. this.hdrFinalPostProcess.dispose(camera);
  52003. }
  52004. if (this.depthOfFieldPostProcess) {
  52005. this.depthOfFieldPostProcess.dispose(camera);
  52006. }
  52007. if (this.motionBlurPostProcess) {
  52008. this.motionBlurPostProcess.dispose(camera);
  52009. }
  52010. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  52011. this.blurHPostProcesses[j].dispose(camera);
  52012. }
  52013. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  52014. this.blurVPostProcesses[j].dispose(camera);
  52015. }
  52016. }
  52017. this.originalPostProcess = null;
  52018. this.downSampleX4PostProcess = null;
  52019. this.brightPassPostProcess = null;
  52020. this.textureAdderPostProcess = null;
  52021. this.textureAdderFinalPostProcess = null;
  52022. this.volumetricLightPostProcess = null;
  52023. this.volumetricLightSmoothXPostProcess = null;
  52024. this.volumetricLightSmoothYPostProcess = null;
  52025. this.volumetricLightMergePostProces = null;
  52026. this.volumetricLightFinalPostProcess = null;
  52027. this.lensFlarePostProcess = null;
  52028. this.lensFlareComposePostProcess = null;
  52029. this.luminancePostProcess = null;
  52030. this.hdrPostProcess = null;
  52031. this.hdrFinalPostProcess = null;
  52032. this.depthOfFieldPostProcess = null;
  52033. this.motionBlurPostProcess = null;
  52034. this.luminanceDownSamplePostProcesses = [];
  52035. this.blurHPostProcesses = [];
  52036. this.blurVPostProcesses = [];
  52037. };
  52038. // Dispose
  52039. StandardRenderingPipeline.prototype.dispose = function () {
  52040. this._disposePostProcesses();
  52041. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  52042. _super.prototype.dispose.call(this);
  52043. };
  52044. // Serialize rendering pipeline
  52045. StandardRenderingPipeline.prototype.serialize = function () {
  52046. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52047. serializationObject.customType = "StandardRenderingPipeline";
  52048. return serializationObject;
  52049. };
  52050. /**
  52051. * Static members
  52052. */
  52053. // Parse serialized pipeline
  52054. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  52055. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  52056. };
  52057. return StandardRenderingPipeline;
  52058. }(BABYLON.PostProcessRenderPipeline));
  52059. // Luminance steps
  52060. StandardRenderingPipeline.LuminanceSteps = 6;
  52061. __decorate([
  52062. BABYLON.serialize()
  52063. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  52064. __decorate([
  52065. BABYLON.serialize()
  52066. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  52067. __decorate([
  52068. BABYLON.serialize()
  52069. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  52070. __decorate([
  52071. BABYLON.serialize()
  52072. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  52073. __decorate([
  52074. BABYLON.serializeAsTexture("lensTexture")
  52075. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  52076. __decorate([
  52077. BABYLON.serialize()
  52078. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  52079. __decorate([
  52080. BABYLON.serialize()
  52081. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  52082. __decorate([
  52083. BABYLON.serialize()
  52084. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  52085. __decorate([
  52086. BABYLON.serialize()
  52087. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  52088. __decorate([
  52089. BABYLON.serialize()
  52090. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  52091. __decorate([
  52092. BABYLON.serialize()
  52093. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  52094. __decorate([
  52095. BABYLON.serializeAsTexture("lensColorTexture")
  52096. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  52097. __decorate([
  52098. BABYLON.serialize()
  52099. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  52100. __decorate([
  52101. BABYLON.serialize()
  52102. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  52103. __decorate([
  52104. BABYLON.serialize()
  52105. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  52106. __decorate([
  52107. BABYLON.serialize()
  52108. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  52109. __decorate([
  52110. BABYLON.serializeAsTexture("lensStarTexture")
  52111. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  52112. __decorate([
  52113. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  52114. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  52115. __decorate([
  52116. BABYLON.serialize()
  52117. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  52118. __decorate([
  52119. BABYLON.serialize()
  52120. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  52121. __decorate([
  52122. BABYLON.serialize()
  52123. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  52124. __decorate([
  52125. BABYLON.serialize()
  52126. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  52127. __decorate([
  52128. BABYLON.serialize()
  52129. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  52130. __decorate([
  52131. BABYLON.serialize()
  52132. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  52133. __decorate([
  52134. BABYLON.serialize()
  52135. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  52136. __decorate([
  52137. BABYLON.serialize()
  52138. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  52139. __decorate([
  52140. BABYLON.serialize()
  52141. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  52142. __decorate([
  52143. BABYLON.serialize()
  52144. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  52145. __decorate([
  52146. BABYLON.serialize()
  52147. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  52148. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  52149. })(BABYLON || (BABYLON = {}));
  52150. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  52151. var BABYLON;
  52152. (function (BABYLON) {
  52153. var FxaaPostProcess = (function (_super) {
  52154. __extends(FxaaPostProcess, _super);
  52155. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52156. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52157. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  52158. _this.onApplyObservable.add(function (effect) {
  52159. var texelSize = _this.texelSize;
  52160. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  52161. });
  52162. return _this;
  52163. }
  52164. return FxaaPostProcess;
  52165. }(BABYLON.PostProcess));
  52166. BABYLON.FxaaPostProcess = FxaaPostProcess;
  52167. })(BABYLON || (BABYLON = {}));
  52168. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  52169. var BABYLON;
  52170. (function (BABYLON) {
  52171. var DefaultRenderingPipeline = (function (_super) {
  52172. __extends(DefaultRenderingPipeline, _super);
  52173. /**
  52174. * @constructor
  52175. * @param {string} name - The rendering pipeline name
  52176. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52177. * @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)
  52178. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52179. */
  52180. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  52181. var _this = _super.call(this, scene.getEngine(), name) || this;
  52182. _this.PassPostProcessId = "PassPostProcessEffect";
  52183. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  52184. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  52185. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  52186. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  52187. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  52188. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  52189. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  52190. // IAnimatable
  52191. _this.animations = [];
  52192. // Values
  52193. _this._bloomEnabled = false;
  52194. _this._fxaaEnabled = false;
  52195. _this._imageProcessingEnabled = true;
  52196. _this._bloomScale = 0.6;
  52197. /**
  52198. * Specifies the size of the bloom blur kernel, relative to the final output size
  52199. */
  52200. _this.bloomKernel = 64;
  52201. /**
  52202. * Specifies the weight of the bloom in the final rendering
  52203. */
  52204. _this._bloomWeight = 0.15;
  52205. _this._cameras = cameras || [];
  52206. // Initialize
  52207. _this._scene = scene;
  52208. var caps = _this._scene.getEngine().getCaps();
  52209. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  52210. // Misc
  52211. if (_this._hdr) {
  52212. if (caps.textureHalfFloatRender) {
  52213. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52214. }
  52215. else if (caps.textureFloatRender) {
  52216. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52217. }
  52218. }
  52219. else {
  52220. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52221. }
  52222. // Attach
  52223. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52224. _this._buildPipeline();
  52225. return _this;
  52226. }
  52227. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  52228. get: function () {
  52229. return this._bloomWeight;
  52230. },
  52231. set: function (value) {
  52232. if (this._bloomWeight === value) {
  52233. return;
  52234. }
  52235. this._bloomWeight = value;
  52236. if (this._hdr && this.copyBack) {
  52237. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  52238. }
  52239. },
  52240. enumerable: true,
  52241. configurable: true
  52242. });
  52243. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  52244. get: function () {
  52245. return this._bloomScale;
  52246. },
  52247. set: function (value) {
  52248. if (this._bloomScale === value) {
  52249. return;
  52250. }
  52251. this._bloomScale = value;
  52252. this._buildPipeline();
  52253. },
  52254. enumerable: true,
  52255. configurable: true
  52256. });
  52257. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  52258. get: function () {
  52259. return this._bloomEnabled;
  52260. },
  52261. set: function (enabled) {
  52262. if (this._bloomEnabled === enabled) {
  52263. return;
  52264. }
  52265. this._bloomEnabled = enabled;
  52266. this._buildPipeline();
  52267. },
  52268. enumerable: true,
  52269. configurable: true
  52270. });
  52271. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  52272. get: function () {
  52273. return this._fxaaEnabled;
  52274. },
  52275. set: function (enabled) {
  52276. if (this._fxaaEnabled === enabled) {
  52277. return;
  52278. }
  52279. this._fxaaEnabled = enabled;
  52280. this._buildPipeline();
  52281. },
  52282. enumerable: true,
  52283. configurable: true
  52284. });
  52285. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  52286. get: function () {
  52287. return this._imageProcessingEnabled;
  52288. },
  52289. set: function (enabled) {
  52290. if (this._imageProcessingEnabled === enabled) {
  52291. return;
  52292. }
  52293. this._imageProcessingEnabled = enabled;
  52294. this._buildPipeline();
  52295. },
  52296. enumerable: true,
  52297. configurable: true
  52298. });
  52299. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  52300. var _this = this;
  52301. var engine = this._scene.getEngine();
  52302. this._disposePostProcesses();
  52303. this._reset();
  52304. if (this.bloomEnabled) {
  52305. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52306. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  52307. if (!this._hdr) {
  52308. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52309. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  52310. this.highlights.autoClear = false;
  52311. this.highlights.alwaysForcePOT = true;
  52312. }
  52313. 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);
  52314. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  52315. this.blurX.alwaysForcePOT = true;
  52316. this.blurX.autoClear = false;
  52317. this.blurX.onActivateObservable.add(function () {
  52318. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  52319. _this.blurX.kernel = _this.bloomKernel * dw;
  52320. });
  52321. 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);
  52322. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  52323. this.blurY.alwaysForcePOT = true;
  52324. this.blurY.autoClear = false;
  52325. this.blurY.onActivateObservable.add(function () {
  52326. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  52327. _this.blurY.kernel = _this.bloomKernel * dh;
  52328. });
  52329. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52330. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  52331. this.copyBack.alwaysForcePOT = true;
  52332. if (this._hdr) {
  52333. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  52334. var w = this.bloomWeight;
  52335. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  52336. }
  52337. else {
  52338. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  52339. }
  52340. this.copyBack.autoClear = false;
  52341. }
  52342. if (this._imageProcessingEnabled) {
  52343. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52344. if (this._hdr) {
  52345. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  52346. }
  52347. }
  52348. if (this.fxaaEnabled) {
  52349. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52350. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  52351. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  52352. }
  52353. else {
  52354. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52355. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  52356. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  52357. }
  52358. if (this.bloomEnabled) {
  52359. if (this._hdr) {
  52360. this.copyBack.shareOutputWith(this.blurX);
  52361. if (this.imageProcessing) {
  52362. this.imageProcessing.shareOutputWith(this.pass);
  52363. this.imageProcessing.autoClear = false;
  52364. }
  52365. else if (this.fxaa) {
  52366. this.fxaa.shareOutputWith(this.pass);
  52367. }
  52368. else {
  52369. this.finalMerge.shareOutputWith(this.pass);
  52370. }
  52371. }
  52372. else {
  52373. if (this.fxaa) {
  52374. this.fxaa.shareOutputWith(this.pass);
  52375. }
  52376. else {
  52377. this.finalMerge.shareOutputWith(this.pass);
  52378. }
  52379. }
  52380. }
  52381. if (this._cameras !== null) {
  52382. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  52383. }
  52384. };
  52385. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  52386. for (var i = 0; i < this._cameras.length; i++) {
  52387. var camera = this._cameras[i];
  52388. if (this.pass) {
  52389. this.pass.dispose(camera);
  52390. }
  52391. if (this.highlights) {
  52392. this.highlights.dispose(camera);
  52393. }
  52394. if (this.blurX) {
  52395. this.blurX.dispose(camera);
  52396. }
  52397. if (this.blurY) {
  52398. this.blurY.dispose(camera);
  52399. }
  52400. if (this.copyBack) {
  52401. this.copyBack.dispose(camera);
  52402. }
  52403. if (this.imageProcessing) {
  52404. this.imageProcessing.dispose(camera);
  52405. }
  52406. if (this.fxaa) {
  52407. this.fxaa.dispose(camera);
  52408. }
  52409. if (this.finalMerge) {
  52410. this.finalMerge.dispose(camera);
  52411. }
  52412. }
  52413. this.pass = null;
  52414. this.highlights = null;
  52415. this.blurX = null;
  52416. this.blurY = null;
  52417. this.copyBack = null;
  52418. this.imageProcessing = null;
  52419. this.fxaa = null;
  52420. this.finalMerge = null;
  52421. };
  52422. // Dispose
  52423. DefaultRenderingPipeline.prototype.dispose = function () {
  52424. this._disposePostProcesses();
  52425. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  52426. _super.prototype.dispose.call(this);
  52427. };
  52428. // Serialize rendering pipeline
  52429. DefaultRenderingPipeline.prototype.serialize = function () {
  52430. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52431. serializationObject.customType = "DefaultRenderingPipeline";
  52432. return serializationObject;
  52433. };
  52434. // Parse serialized pipeline
  52435. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  52436. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  52437. };
  52438. return DefaultRenderingPipeline;
  52439. }(BABYLON.PostProcessRenderPipeline));
  52440. __decorate([
  52441. BABYLON.serialize()
  52442. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  52443. __decorate([
  52444. BABYLON.serialize()
  52445. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  52446. __decorate([
  52447. BABYLON.serialize()
  52448. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  52449. __decorate([
  52450. BABYLON.serialize()
  52451. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  52452. __decorate([
  52453. BABYLON.serialize()
  52454. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  52455. __decorate([
  52456. BABYLON.serialize()
  52457. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  52458. __decorate([
  52459. BABYLON.serialize()
  52460. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  52461. __decorate([
  52462. BABYLON.serialize()
  52463. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  52464. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  52465. })(BABYLON || (BABYLON = {}));
  52466. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  52467. var BABYLON;
  52468. (function (BABYLON) {
  52469. var GeometryBufferRenderer = (function () {
  52470. function GeometryBufferRenderer(scene, ratio) {
  52471. if (ratio === void 0) { ratio = 1; }
  52472. this._viewMatrix = BABYLON.Matrix.Zero();
  52473. this._projectionMatrix = BABYLON.Matrix.Zero();
  52474. this._transformMatrix = BABYLON.Matrix.Zero();
  52475. this._worldViewProjection = BABYLON.Matrix.Zero();
  52476. this._enablePosition = false;
  52477. this._scene = scene;
  52478. this._ratio = ratio;
  52479. // Render target
  52480. this._createRenderTargets();
  52481. }
  52482. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  52483. set: function (meshes) {
  52484. this._multiRenderTarget.renderList = meshes;
  52485. },
  52486. enumerable: true,
  52487. configurable: true
  52488. });
  52489. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  52490. get: function () {
  52491. return this._multiRenderTarget.isSupported;
  52492. },
  52493. enumerable: true,
  52494. configurable: true
  52495. });
  52496. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  52497. get: function () {
  52498. return this._enablePosition;
  52499. },
  52500. set: function (enable) {
  52501. this._enablePosition = enable;
  52502. this.dispose();
  52503. this._createRenderTargets();
  52504. },
  52505. enumerable: true,
  52506. configurable: true
  52507. });
  52508. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  52509. var material = subMesh.getMaterial();
  52510. if (material && material.disableDepthWrite) {
  52511. return false;
  52512. }
  52513. var defines = [];
  52514. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  52515. var mesh = subMesh.getMesh();
  52516. var scene = mesh.getScene();
  52517. // Alpha test
  52518. if (material && material.needAlphaTesting()) {
  52519. defines.push("#define ALPHATEST");
  52520. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52521. attribs.push(BABYLON.VertexBuffer.UVKind);
  52522. defines.push("#define UV1");
  52523. }
  52524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52525. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52526. defines.push("#define UV2");
  52527. }
  52528. }
  52529. // Buffers
  52530. if (this._enablePosition) {
  52531. defines.push("#define POSITION");
  52532. }
  52533. // Bones
  52534. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52535. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52536. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52537. if (mesh.numBoneInfluencers > 4) {
  52538. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52539. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52540. }
  52541. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52542. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52543. }
  52544. else {
  52545. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52546. }
  52547. // Instances
  52548. if (useInstances) {
  52549. defines.push("#define INSTANCES");
  52550. attribs.push("world0");
  52551. attribs.push("world1");
  52552. attribs.push("world2");
  52553. attribs.push("world3");
  52554. }
  52555. // Get correct effect
  52556. var join = defines.join("\n");
  52557. if (this._cachedDefines !== join) {
  52558. this._cachedDefines = join;
  52559. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  52560. }
  52561. return this._effect.isReady();
  52562. };
  52563. GeometryBufferRenderer.prototype.getGBuffer = function () {
  52564. return this._multiRenderTarget;
  52565. };
  52566. // Methods
  52567. GeometryBufferRenderer.prototype.dispose = function () {
  52568. this.getGBuffer().dispose();
  52569. };
  52570. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  52571. var _this = this;
  52572. var engine = this._scene.getEngine();
  52573. var count = this._enablePosition ? 3 : 2;
  52574. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  52575. if (!this.isSupported) {
  52576. return null;
  52577. }
  52578. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52579. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52580. this._multiRenderTarget.refreshRate = 1;
  52581. this._multiRenderTarget.renderParticles = false;
  52582. this._multiRenderTarget.renderList = null;
  52583. // set default depth value to 1.0 (far away)
  52584. this._multiRenderTarget.onClearObservable.add(function (engine) {
  52585. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  52586. });
  52587. // Custom render function
  52588. var renderSubMesh = function (subMesh) {
  52589. var mesh = subMesh.getRenderingMesh();
  52590. var scene = _this._scene;
  52591. var engine = scene.getEngine();
  52592. // Culling
  52593. engine.setState(subMesh.getMaterial().backFaceCulling);
  52594. // Managing instances
  52595. var batch = mesh._getInstancesRenderList(subMesh._id);
  52596. if (batch.mustReturn) {
  52597. return;
  52598. }
  52599. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  52600. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52601. engine.enableEffect(_this._effect);
  52602. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  52603. var material = subMesh.getMaterial();
  52604. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52605. _this._effect.setMatrix("view", scene.getViewMatrix());
  52606. // Alpha test
  52607. if (material && material.needAlphaTesting()) {
  52608. var alphaTexture = material.getAlphaTestTexture();
  52609. _this._effect.setTexture("diffuseSampler", alphaTexture);
  52610. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52611. }
  52612. // Bones
  52613. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52614. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52615. }
  52616. // Draw
  52617. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52618. }
  52619. };
  52620. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  52621. var index;
  52622. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52623. renderSubMesh(opaqueSubMeshes.data[index]);
  52624. }
  52625. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52626. renderSubMesh(alphaTestSubMeshes.data[index]);
  52627. }
  52628. };
  52629. };
  52630. return GeometryBufferRenderer;
  52631. }());
  52632. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  52633. })(BABYLON || (BABYLON = {}));
  52634. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  52635. var BABYLON;
  52636. (function (BABYLON) {
  52637. var RefractionPostProcess = (function (_super) {
  52638. __extends(RefractionPostProcess, _super);
  52639. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  52640. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  52641. _this.color = color;
  52642. _this.depth = depth;
  52643. _this.colorLevel = colorLevel;
  52644. _this.onActivateObservable.add(function (cam) {
  52645. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  52646. });
  52647. _this.onApplyObservable.add(function (effect) {
  52648. effect.setColor3("baseColor", _this.color);
  52649. effect.setFloat("depth", _this.depth);
  52650. effect.setFloat("colorLevel", _this.colorLevel);
  52651. effect.setTexture("refractionSampler", _this._refRexture);
  52652. });
  52653. return _this;
  52654. }
  52655. // Methods
  52656. RefractionPostProcess.prototype.dispose = function (camera) {
  52657. if (this._refRexture) {
  52658. this._refRexture.dispose();
  52659. }
  52660. _super.prototype.dispose.call(this, camera);
  52661. };
  52662. return RefractionPostProcess;
  52663. }(BABYLON.PostProcess));
  52664. BABYLON.RefractionPostProcess = RefractionPostProcess;
  52665. })(BABYLON || (BABYLON = {}));
  52666. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  52667. var BABYLON;
  52668. (function (BABYLON) {
  52669. var BlackAndWhitePostProcess = (function (_super) {
  52670. __extends(BlackAndWhitePostProcess, _super);
  52671. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  52672. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  52673. _this.degree = 1;
  52674. _this.onApplyObservable.add(function (effect) {
  52675. effect.setFloat("degree", _this.degree);
  52676. });
  52677. return _this;
  52678. }
  52679. return BlackAndWhitePostProcess;
  52680. }(BABYLON.PostProcess));
  52681. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  52682. })(BABYLON || (BABYLON = {}));
  52683. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  52684. var BABYLON;
  52685. (function (BABYLON) {
  52686. var ConvolutionPostProcess = (function (_super) {
  52687. __extends(ConvolutionPostProcess, _super);
  52688. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  52689. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  52690. _this.kernel = kernel;
  52691. _this.onApply = function (effect) {
  52692. effect.setFloat2("screenSize", _this.width, _this.height);
  52693. effect.setArray("kernel", _this.kernel);
  52694. };
  52695. return _this;
  52696. }
  52697. return ConvolutionPostProcess;
  52698. }(BABYLON.PostProcess));
  52699. // Statics
  52700. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  52701. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  52702. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  52703. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  52704. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  52705. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  52706. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  52707. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  52708. })(BABYLON || (BABYLON = {}));
  52709. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  52710. var BABYLON;
  52711. (function (BABYLON) {
  52712. var FilterPostProcess = (function (_super) {
  52713. __extends(FilterPostProcess, _super);
  52714. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  52715. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  52716. _this.kernelMatrix = kernelMatrix;
  52717. _this.onApply = function (effect) {
  52718. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  52719. };
  52720. return _this;
  52721. }
  52722. return FilterPostProcess;
  52723. }(BABYLON.PostProcess));
  52724. BABYLON.FilterPostProcess = FilterPostProcess;
  52725. })(BABYLON || (BABYLON = {}));
  52726. //# sourceMappingURL=babylon.filterPostProcess.js.map
  52727. var BABYLON;
  52728. (function (BABYLON) {
  52729. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  52730. var VolumetricLightScatteringPostProcess = (function (_super) {
  52731. __extends(VolumetricLightScatteringPostProcess, _super);
  52732. /**
  52733. * @constructor
  52734. * @param {string} name - The post-process name
  52735. * @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)
  52736. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  52737. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  52738. * @param {number} samples - The post-process quality, default 100
  52739. * @param {number} samplingMode - The post-process filtering mode
  52740. * @param {BABYLON.Engine} engine - The babylon engine
  52741. * @param {boolean} reusable - If the post-process is reusable
  52742. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  52743. */
  52744. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  52745. if (samples === void 0) { samples = 100; }
  52746. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52747. 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;
  52748. _this._screenCoordinates = BABYLON.Vector2.Zero();
  52749. /**
  52750. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  52751. * @type {Vector3}
  52752. */
  52753. _this.customMeshPosition = BABYLON.Vector3.Zero();
  52754. /**
  52755. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  52756. * @type {boolean}
  52757. */
  52758. _this.useCustomMeshPosition = false;
  52759. /**
  52760. * If the post-process should inverse the light scattering direction
  52761. * @type {boolean}
  52762. */
  52763. _this.invert = true;
  52764. /**
  52765. * Array containing the excluded meshes not rendered in the internal pass
  52766. */
  52767. _this.excludedMeshes = new Array();
  52768. /**
  52769. * Controls the overall intensity of the post-process
  52770. * @type {number}
  52771. */
  52772. _this.exposure = 0.3;
  52773. /**
  52774. * Dissipates each sample's contribution in range [0, 1]
  52775. * @type {number}
  52776. */
  52777. _this.decay = 0.96815;
  52778. /**
  52779. * Controls the overall intensity of each sample
  52780. * @type {number}
  52781. */
  52782. _this.weight = 0.58767;
  52783. /**
  52784. * Controls the density of each sample
  52785. * @type {number}
  52786. */
  52787. _this.density = 0.926;
  52788. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  52789. var engine = scene.getEngine();
  52790. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52791. // Configure mesh
  52792. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  52793. // Configure
  52794. _this._createPass(scene, ratio.passRatio || ratio);
  52795. _this.onActivate = function (camera) {
  52796. if (!_this.isSupported) {
  52797. _this.dispose(camera);
  52798. }
  52799. _this.onActivate = null;
  52800. };
  52801. _this.onApplyObservable.add(function (effect) {
  52802. _this._updateMeshScreenCoordinates(scene);
  52803. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  52804. effect.setFloat("exposure", _this.exposure);
  52805. effect.setFloat("decay", _this.decay);
  52806. effect.setFloat("weight", _this.weight);
  52807. effect.setFloat("density", _this.density);
  52808. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  52809. });
  52810. return _this;
  52811. }
  52812. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  52813. get: function () {
  52814. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52815. return false;
  52816. },
  52817. set: function (useDiffuseColor) {
  52818. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52819. },
  52820. enumerable: true,
  52821. configurable: true
  52822. });
  52823. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  52824. var mesh = subMesh.getMesh();
  52825. // Render this.mesh as default
  52826. if (mesh === this.mesh) {
  52827. return mesh.material.isReady(mesh);
  52828. }
  52829. var defines = [];
  52830. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52831. var material = subMesh.getMaterial();
  52832. var needUV = false;
  52833. // Alpha test
  52834. if (material) {
  52835. if (material.needAlphaTesting()) {
  52836. defines.push("#define ALPHATEST");
  52837. }
  52838. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52839. attribs.push(BABYLON.VertexBuffer.UVKind);
  52840. defines.push("#define UV1");
  52841. }
  52842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52843. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52844. defines.push("#define UV2");
  52845. }
  52846. }
  52847. // Bones
  52848. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52849. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52850. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52851. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52852. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52853. }
  52854. else {
  52855. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52856. }
  52857. // Instances
  52858. if (useInstances) {
  52859. defines.push("#define INSTANCES");
  52860. attribs.push("world0");
  52861. attribs.push("world1");
  52862. attribs.push("world2");
  52863. attribs.push("world3");
  52864. }
  52865. // Get correct effect
  52866. var join = defines.join("\n");
  52867. if (this._cachedDefines !== join) {
  52868. this._cachedDefines = join;
  52869. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  52870. }
  52871. return this._volumetricLightScatteringPass.isReady();
  52872. };
  52873. /**
  52874. * Sets the new light position for light scattering effect
  52875. * @param {BABYLON.Vector3} The new custom light position
  52876. */
  52877. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  52878. this.customMeshPosition = position;
  52879. };
  52880. /**
  52881. * Returns the light position for light scattering effect
  52882. * @return {BABYLON.Vector3} The custom light position
  52883. */
  52884. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  52885. return this.customMeshPosition;
  52886. };
  52887. /**
  52888. * Disposes the internal assets and detaches the post-process from the camera
  52889. */
  52890. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  52891. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  52892. if (rttIndex !== -1) {
  52893. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  52894. }
  52895. this._volumetricLightScatteringRTT.dispose();
  52896. _super.prototype.dispose.call(this, camera);
  52897. };
  52898. /**
  52899. * Returns the render target texture used by the post-process
  52900. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52901. */
  52902. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52903. return this._volumetricLightScatteringRTT;
  52904. };
  52905. // Private methods
  52906. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52907. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52908. return true;
  52909. }
  52910. return false;
  52911. };
  52912. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52913. var _this = this;
  52914. var engine = scene.getEngine();
  52915. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52916. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52917. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52918. this._volumetricLightScatteringRTT.renderList = null;
  52919. this._volumetricLightScatteringRTT.renderParticles = false;
  52920. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52921. // Custom render function for submeshes
  52922. var renderSubMesh = function (subMesh) {
  52923. var mesh = subMesh.getRenderingMesh();
  52924. if (_this._meshExcluded(mesh)) {
  52925. return;
  52926. }
  52927. var scene = mesh.getScene();
  52928. var engine = scene.getEngine();
  52929. // Culling
  52930. engine.setState(subMesh.getMaterial().backFaceCulling);
  52931. // Managing instances
  52932. var batch = mesh._getInstancesRenderList(subMesh._id);
  52933. if (batch.mustReturn) {
  52934. return;
  52935. }
  52936. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  52937. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52938. var effect = _this._volumetricLightScatteringPass;
  52939. if (mesh === _this.mesh) {
  52940. if (subMesh.effect) {
  52941. effect = subMesh.effect;
  52942. }
  52943. else {
  52944. effect = subMesh.getMaterial().getEffect();
  52945. }
  52946. }
  52947. engine.enableEffect(effect);
  52948. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52949. if (mesh === _this.mesh) {
  52950. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52951. }
  52952. else {
  52953. var material = subMesh.getMaterial();
  52954. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52955. // Alpha test
  52956. if (material && material.needAlphaTesting()) {
  52957. var alphaTexture = material.getAlphaTestTexture();
  52958. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52959. if (alphaTexture) {
  52960. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52961. }
  52962. }
  52963. // Bones
  52964. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52965. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52966. }
  52967. }
  52968. // Draw
  52969. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52970. }
  52971. };
  52972. // Render target texture callbacks
  52973. var savedSceneClearColor;
  52974. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52975. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52976. savedSceneClearColor = scene.clearColor;
  52977. scene.clearColor = sceneClearColor;
  52978. });
  52979. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52980. scene.clearColor = savedSceneClearColor;
  52981. });
  52982. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52983. var engine = scene.getEngine();
  52984. var index;
  52985. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52986. renderSubMesh(opaqueSubMeshes.data[index]);
  52987. }
  52988. engine.setAlphaTesting(true);
  52989. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52990. renderSubMesh(alphaTestSubMeshes.data[index]);
  52991. }
  52992. engine.setAlphaTesting(false);
  52993. if (transparentSubMeshes.length) {
  52994. // Sort sub meshes
  52995. for (index = 0; index < transparentSubMeshes.length; index++) {
  52996. var submesh = transparentSubMeshes.data[index];
  52997. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52998. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52999. }
  53000. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  53001. sortedArray.sort(function (a, b) {
  53002. // Alpha index first
  53003. if (a._alphaIndex > b._alphaIndex) {
  53004. return 1;
  53005. }
  53006. if (a._alphaIndex < b._alphaIndex) {
  53007. return -1;
  53008. }
  53009. // Then distance to camera
  53010. if (a._distanceToCamera < b._distanceToCamera) {
  53011. return 1;
  53012. }
  53013. if (a._distanceToCamera > b._distanceToCamera) {
  53014. return -1;
  53015. }
  53016. return 0;
  53017. });
  53018. // Render sub meshes
  53019. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53020. for (index = 0; index < sortedArray.length; index++) {
  53021. renderSubMesh(sortedArray[index]);
  53022. }
  53023. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53024. }
  53025. };
  53026. };
  53027. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  53028. var transform = scene.getTransformMatrix();
  53029. var meshPosition;
  53030. if (this.useCustomMeshPosition) {
  53031. meshPosition = this.customMeshPosition;
  53032. }
  53033. else if (this.attachedNode) {
  53034. meshPosition = this.attachedNode.position;
  53035. }
  53036. else {
  53037. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  53038. }
  53039. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  53040. this._screenCoordinates.x = pos.x / this._viewPort.width;
  53041. this._screenCoordinates.y = pos.y / this._viewPort.height;
  53042. if (this.invert)
  53043. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  53044. };
  53045. // Static methods
  53046. /**
  53047. * Creates a default mesh for the Volumeric Light Scattering post-process
  53048. * @param {string} The mesh name
  53049. * @param {BABYLON.Scene} The scene where to create the mesh
  53050. * @return {BABYLON.Mesh} the default mesh
  53051. */
  53052. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  53053. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  53054. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  53055. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  53056. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  53057. mesh.material = material;
  53058. return mesh;
  53059. };
  53060. return VolumetricLightScatteringPostProcess;
  53061. }(BABYLON.PostProcess));
  53062. __decorate([
  53063. BABYLON.serializeAsVector3()
  53064. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  53065. __decorate([
  53066. BABYLON.serialize()
  53067. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  53068. __decorate([
  53069. BABYLON.serialize()
  53070. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  53071. __decorate([
  53072. BABYLON.serializeAsMeshReference()
  53073. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  53074. __decorate([
  53075. BABYLON.serialize()
  53076. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  53077. __decorate([
  53078. BABYLON.serialize()
  53079. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  53080. __decorate([
  53081. BABYLON.serialize()
  53082. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  53083. __decorate([
  53084. BABYLON.serialize()
  53085. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  53086. __decorate([
  53087. BABYLON.serialize()
  53088. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  53089. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  53090. })(BABYLON || (BABYLON = {}));
  53091. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  53092. //
  53093. // This post-process allows the modification of rendered colors by using
  53094. // a 'look-up table' (LUT). This effect is also called Color Grading.
  53095. //
  53096. // The object needs to be provided an url to a texture containing the color
  53097. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  53098. // Use an image editing software to tweak the LUT to match your needs.
  53099. //
  53100. // For an example of a color LUT, see here:
  53101. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  53102. // For explanations on color grading, see here:
  53103. // http://udn.epicgames.com/Three/ColorGrading.html
  53104. //
  53105. var BABYLON;
  53106. (function (BABYLON) {
  53107. var ColorCorrectionPostProcess = (function (_super) {
  53108. __extends(ColorCorrectionPostProcess, _super);
  53109. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  53110. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  53111. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53112. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  53113. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53114. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53115. _this.onApply = function (effect) {
  53116. effect.setTexture("colorTable", _this._colorTableTexture);
  53117. };
  53118. return _this;
  53119. }
  53120. return ColorCorrectionPostProcess;
  53121. }(BABYLON.PostProcess));
  53122. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  53123. })(BABYLON || (BABYLON = {}));
  53124. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  53125. var BABYLON;
  53126. (function (BABYLON) {
  53127. var TonemappingOperator;
  53128. (function (TonemappingOperator) {
  53129. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  53130. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  53131. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  53132. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  53133. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  53134. ;
  53135. var TonemapPostProcess = (function (_super) {
  53136. __extends(TonemapPostProcess, _super);
  53137. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  53138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53139. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53140. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  53141. _this._operator = _operator;
  53142. _this.exposureAdjustment = exposureAdjustment;
  53143. var defines = "#define ";
  53144. if (_this._operator === TonemappingOperator.Hable)
  53145. defines += "HABLE_TONEMAPPING";
  53146. else if (_this._operator === TonemappingOperator.Reinhard)
  53147. defines += "REINHARD_TONEMAPPING";
  53148. else if (_this._operator === TonemappingOperator.HejiDawson)
  53149. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  53150. else if (_this._operator === TonemappingOperator.Photographic)
  53151. defines += "PHOTOGRAPHIC_TONEMAPPING";
  53152. //sadly a second call to create the effect.
  53153. _this.updateEffect(defines);
  53154. _this.onApply = function (effect) {
  53155. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  53156. };
  53157. return _this;
  53158. }
  53159. return TonemapPostProcess;
  53160. }(BABYLON.PostProcess));
  53161. BABYLON.TonemapPostProcess = TonemapPostProcess;
  53162. })(BABYLON || (BABYLON = {}));
  53163. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  53164. var BABYLON;
  53165. (function (BABYLON) {
  53166. var DisplayPassPostProcess = (function (_super) {
  53167. __extends(DisplayPassPostProcess, _super);
  53168. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  53169. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  53170. }
  53171. return DisplayPassPostProcess;
  53172. }(BABYLON.PostProcess));
  53173. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  53174. })(BABYLON || (BABYLON = {}));
  53175. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  53176. var BABYLON;
  53177. (function (BABYLON) {
  53178. var HighlightsPostProcess = (function (_super) {
  53179. __extends(HighlightsPostProcess, _super);
  53180. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53181. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53182. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  53183. }
  53184. return HighlightsPostProcess;
  53185. }(BABYLON.PostProcess));
  53186. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  53187. })(BABYLON || (BABYLON = {}));
  53188. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  53189. var BABYLON;
  53190. (function (BABYLON) {
  53191. var ImageProcessingPostProcess = (function (_super) {
  53192. __extends(ImageProcessingPostProcess, _super);
  53193. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53194. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53195. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  53196. _this._fromLinearSpace = true;
  53197. /**
  53198. * Defines cache preventing GC.
  53199. */
  53200. _this._defines = {
  53201. IMAGEPROCESSING: false,
  53202. VIGNETTE: false,
  53203. VIGNETTEBLENDMODEMULTIPLY: false,
  53204. VIGNETTEBLENDMODEOPAQUE: false,
  53205. TONEMAPPING: false,
  53206. CONTRAST: false,
  53207. COLORCURVES: false,
  53208. COLORGRADING: false,
  53209. FROMLINEARSPACE: false,
  53210. SAMPLER3DGREENDEPTH: false,
  53211. SAMPLER3DBGRMAP: false,
  53212. IMAGEPROCESSINGPOSTPROCESS: false,
  53213. EXPOSURE: false,
  53214. };
  53215. // Setup the default processing configuration to the scene.
  53216. _this._attachImageProcessingConfiguration(null);
  53217. _this.imageProcessingConfiguration.applyByPostProcess = true;
  53218. _this._updateParameters();
  53219. _this.onApply = function (effect) {
  53220. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  53221. };
  53222. return _this;
  53223. }
  53224. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  53225. /**
  53226. * Gets the image processing configuration used either in this material.
  53227. */
  53228. get: function () {
  53229. return this._imageProcessingConfiguration;
  53230. },
  53231. /**
  53232. * Sets the Default image processing configuration used either in the this material.
  53233. *
  53234. * If sets to null, the scene one is in use.
  53235. */
  53236. set: function (value) {
  53237. this._attachImageProcessingConfiguration(value);
  53238. },
  53239. enumerable: true,
  53240. configurable: true
  53241. });
  53242. /**
  53243. * Attaches a new image processing configuration to the PBR Material.
  53244. * @param configuration
  53245. */
  53246. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration) {
  53247. var _this = this;
  53248. if (configuration === this._imageProcessingConfiguration) {
  53249. return;
  53250. }
  53251. // Detaches observer.
  53252. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  53253. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  53254. }
  53255. // Pick the scene configuration if needed.
  53256. if (!configuration) {
  53257. var camera = this.getCamera();
  53258. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  53259. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  53260. }
  53261. else {
  53262. this._imageProcessingConfiguration = configuration;
  53263. }
  53264. // Attaches observer.
  53265. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  53266. _this._updateParameters();
  53267. });
  53268. // Ensure the effect will be rebuilt.
  53269. this._updateParameters();
  53270. };
  53271. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  53272. /**
  53273. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  53274. */
  53275. get: function () {
  53276. return this.imageProcessingConfiguration.colorCurves;
  53277. },
  53278. /**
  53279. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  53280. */
  53281. set: function (value) {
  53282. this.imageProcessingConfiguration.colorCurves = value;
  53283. },
  53284. enumerable: true,
  53285. configurable: true
  53286. });
  53287. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  53288. /**
  53289. * Gets wether the color curves effect is enabled.
  53290. */
  53291. get: function () {
  53292. return this.imageProcessingConfiguration.colorCurvesEnabled;
  53293. },
  53294. /**
  53295. * Sets wether the color curves effect is enabled.
  53296. */
  53297. set: function (value) {
  53298. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  53299. },
  53300. enumerable: true,
  53301. configurable: true
  53302. });
  53303. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  53304. /**
  53305. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  53306. */
  53307. get: function () {
  53308. return this.imageProcessingConfiguration.colorGradingTexture;
  53309. },
  53310. /**
  53311. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  53312. */
  53313. set: function (value) {
  53314. this.imageProcessingConfiguration.colorGradingTexture = value;
  53315. },
  53316. enumerable: true,
  53317. configurable: true
  53318. });
  53319. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  53320. /**
  53321. * Gets wether the color grading effect is enabled.
  53322. */
  53323. get: function () {
  53324. return this.imageProcessingConfiguration.colorGradingEnabled;
  53325. },
  53326. /**
  53327. * Gets wether the color grading effect is enabled.
  53328. */
  53329. set: function (value) {
  53330. this.imageProcessingConfiguration.colorGradingEnabled = value;
  53331. },
  53332. enumerable: true,
  53333. configurable: true
  53334. });
  53335. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  53336. /**
  53337. * Gets exposure used in the effect.
  53338. */
  53339. get: function () {
  53340. return this.imageProcessingConfiguration.exposure;
  53341. },
  53342. /**
  53343. * Sets exposure used in the effect.
  53344. */
  53345. set: function (value) {
  53346. this.imageProcessingConfiguration.exposure = value;
  53347. },
  53348. enumerable: true,
  53349. configurable: true
  53350. });
  53351. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  53352. /**
  53353. * Gets wether tonemapping is enabled or not.
  53354. */
  53355. get: function () {
  53356. return this._imageProcessingConfiguration.toneMappingEnabled;
  53357. },
  53358. /**
  53359. * Sets wether tonemapping is enabled or not
  53360. */
  53361. set: function (value) {
  53362. this._imageProcessingConfiguration.toneMappingEnabled = value;
  53363. },
  53364. enumerable: true,
  53365. configurable: true
  53366. });
  53367. ;
  53368. ;
  53369. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  53370. /**
  53371. * Gets contrast used in the effect.
  53372. */
  53373. get: function () {
  53374. return this.imageProcessingConfiguration.contrast;
  53375. },
  53376. /**
  53377. * Sets contrast used in the effect.
  53378. */
  53379. set: function (value) {
  53380. this.imageProcessingConfiguration.contrast = value;
  53381. },
  53382. enumerable: true,
  53383. configurable: true
  53384. });
  53385. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  53386. /**
  53387. * Gets Vignette stretch size.
  53388. */
  53389. get: function () {
  53390. return this.imageProcessingConfiguration.vignetteStretch;
  53391. },
  53392. /**
  53393. * Sets Vignette stretch size.
  53394. */
  53395. set: function (value) {
  53396. this.imageProcessingConfiguration.vignetteStretch = value;
  53397. },
  53398. enumerable: true,
  53399. configurable: true
  53400. });
  53401. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  53402. /**
  53403. * Gets Vignette centre X Offset.
  53404. */
  53405. get: function () {
  53406. return this.imageProcessingConfiguration.vignetteCentreX;
  53407. },
  53408. /**
  53409. * Sets Vignette centre X Offset.
  53410. */
  53411. set: function (value) {
  53412. this.imageProcessingConfiguration.vignetteCentreX = value;
  53413. },
  53414. enumerable: true,
  53415. configurable: true
  53416. });
  53417. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  53418. /**
  53419. * Gets Vignette centre Y Offset.
  53420. */
  53421. get: function () {
  53422. return this.imageProcessingConfiguration.vignetteCentreY;
  53423. },
  53424. /**
  53425. * Sets Vignette centre Y Offset.
  53426. */
  53427. set: function (value) {
  53428. this.imageProcessingConfiguration.vignetteCentreY = value;
  53429. },
  53430. enumerable: true,
  53431. configurable: true
  53432. });
  53433. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  53434. /**
  53435. * Gets Vignette weight or intensity of the vignette effect.
  53436. */
  53437. get: function () {
  53438. return this.imageProcessingConfiguration.vignetteWeight;
  53439. },
  53440. /**
  53441. * Sets Vignette weight or intensity of the vignette effect.
  53442. */
  53443. set: function (value) {
  53444. this.imageProcessingConfiguration.vignetteWeight = value;
  53445. },
  53446. enumerable: true,
  53447. configurable: true
  53448. });
  53449. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  53450. /**
  53451. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  53452. * if vignetteEnabled is set to true.
  53453. */
  53454. get: function () {
  53455. return this.imageProcessingConfiguration.vignetteColor;
  53456. },
  53457. /**
  53458. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  53459. * if vignetteEnabled is set to true.
  53460. */
  53461. set: function (value) {
  53462. this.imageProcessingConfiguration.vignetteColor = value;
  53463. },
  53464. enumerable: true,
  53465. configurable: true
  53466. });
  53467. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  53468. /**
  53469. * Gets Camera field of view used by the Vignette effect.
  53470. */
  53471. get: function () {
  53472. return this.imageProcessingConfiguration.vignetteCameraFov;
  53473. },
  53474. /**
  53475. * Sets Camera field of view used by the Vignette effect.
  53476. */
  53477. set: function (value) {
  53478. this.imageProcessingConfiguration.vignetteCameraFov = value;
  53479. },
  53480. enumerable: true,
  53481. configurable: true
  53482. });
  53483. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  53484. /**
  53485. * Gets the vignette blend mode allowing different kind of effect.
  53486. */
  53487. get: function () {
  53488. return this.imageProcessingConfiguration.vignetteBlendMode;
  53489. },
  53490. /**
  53491. * Sets the vignette blend mode allowing different kind of effect.
  53492. */
  53493. set: function (value) {
  53494. this.imageProcessingConfiguration.vignetteBlendMode = value;
  53495. },
  53496. enumerable: true,
  53497. configurable: true
  53498. });
  53499. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  53500. /**
  53501. * Gets wether the vignette effect is enabled.
  53502. */
  53503. get: function () {
  53504. return this.imageProcessingConfiguration.vignetteEnabled;
  53505. },
  53506. /**
  53507. * Sets wether the vignette effect is enabled.
  53508. */
  53509. set: function (value) {
  53510. this.imageProcessingConfiguration.vignetteEnabled = value;
  53511. },
  53512. enumerable: true,
  53513. configurable: true
  53514. });
  53515. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  53516. /**
  53517. * Gets wether the input of the processing is in Gamma or Linear Space.
  53518. */
  53519. get: function () {
  53520. return this._fromLinearSpace;
  53521. },
  53522. /**
  53523. * Sets wether the input of the processing is in Gamma or Linear Space.
  53524. */
  53525. set: function (value) {
  53526. if (this._fromLinearSpace === value) {
  53527. return;
  53528. }
  53529. this._fromLinearSpace = value;
  53530. this._updateParameters();
  53531. },
  53532. enumerable: true,
  53533. configurable: true
  53534. });
  53535. ImageProcessingPostProcess.prototype._updateParameters = function () {
  53536. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  53537. this.imageProcessingConfiguration.prepareDefines(this._defines);
  53538. var defines = "";
  53539. for (var define in this._defines) {
  53540. if (this._defines[define]) {
  53541. defines += "#define " + define + ";\r\n";
  53542. }
  53543. }
  53544. var samplers = ["textureSampler"];
  53545. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  53546. var uniforms = ["scale"];
  53547. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  53548. this.updateEffect(defines, uniforms, samplers);
  53549. };
  53550. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  53551. _super.prototype.dispose.call(this, camera);
  53552. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  53553. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  53554. }
  53555. this.imageProcessingConfiguration.applyByPostProcess = false;
  53556. };
  53557. return ImageProcessingPostProcess;
  53558. }(BABYLON.PostProcess));
  53559. __decorate([
  53560. BABYLON.serialize()
  53561. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  53562. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  53563. })(BABYLON || (BABYLON = {}));
  53564. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  53565. var BABYLON;
  53566. (function (BABYLON) {
  53567. var BlurPostProcess = (function (_super) {
  53568. __extends(BlurPostProcess, _super);
  53569. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  53570. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53571. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53572. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  53573. _this.direction = direction;
  53574. _this._packedFloat = false;
  53575. _this.onApplyObservable.add(function (effect) {
  53576. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  53577. });
  53578. _this.kernel = kernel;
  53579. return _this;
  53580. }
  53581. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  53582. /**
  53583. * Gets the length in pixels of the blur sample region
  53584. */
  53585. get: function () {
  53586. return this._idealKernel;
  53587. },
  53588. /**
  53589. * Sets the length in pixels of the blur sample region
  53590. */
  53591. set: function (v) {
  53592. if (this._idealKernel === v) {
  53593. return;
  53594. }
  53595. v = Math.max(v, 1);
  53596. this._idealKernel = v;
  53597. this._kernel = this._nearestBestKernel(v);
  53598. this._updateParameters();
  53599. },
  53600. enumerable: true,
  53601. configurable: true
  53602. });
  53603. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  53604. /**
  53605. * Gets wether or not the blur is unpacking/repacking floats
  53606. */
  53607. get: function () {
  53608. return this._packedFloat;
  53609. },
  53610. /**
  53611. * Sets wether or not the blur needs to unpack/repack floats
  53612. */
  53613. set: function (v) {
  53614. if (this._packedFloat === v) {
  53615. return;
  53616. }
  53617. this._packedFloat = v;
  53618. this._updateParameters();
  53619. },
  53620. enumerable: true,
  53621. configurable: true
  53622. });
  53623. BlurPostProcess.prototype._updateParameters = function () {
  53624. // Generate sampling offsets and weights
  53625. var N = this._kernel;
  53626. var centerIndex = (N - 1) / 2;
  53627. // Generate Gaussian sampling weights over kernel
  53628. var offsets = [];
  53629. var weights = [];
  53630. var totalWeight = 0;
  53631. for (var i = 0; i < N; i++) {
  53632. var u = i / (N - 1);
  53633. var w = this._gaussianWeight(u * 2.0 - 1);
  53634. offsets[i] = (i - centerIndex);
  53635. weights[i] = w;
  53636. totalWeight += w;
  53637. }
  53638. // Normalize weights
  53639. for (var i = 0; i < weights.length; i++) {
  53640. weights[i] /= totalWeight;
  53641. }
  53642. // Optimize: combine samples to take advantage of hardware linear sampling
  53643. // Walk from left to center, combining pairs (symmetrically)
  53644. var linearSamplingWeights = [];
  53645. var linearSamplingOffsets = [];
  53646. var linearSamplingMap = [];
  53647. for (var i = 0; i <= centerIndex; i += 2) {
  53648. var j = Math.min(i + 1, Math.floor(centerIndex));
  53649. var singleCenterSample = i === j;
  53650. if (singleCenterSample) {
  53651. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  53652. }
  53653. else {
  53654. var sharedCell = j === centerIndex;
  53655. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  53656. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  53657. if (offsetLinear === 0) {
  53658. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  53659. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  53660. }
  53661. else {
  53662. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  53663. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  53664. }
  53665. }
  53666. }
  53667. for (var i = 0; i < linearSamplingMap.length; i++) {
  53668. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  53669. linearSamplingWeights[i] = linearSamplingMap[i].w;
  53670. }
  53671. // Replace with optimized
  53672. offsets = linearSamplingOffsets;
  53673. weights = linearSamplingWeights;
  53674. // Generate shaders
  53675. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  53676. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  53677. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  53678. var defines = "";
  53679. for (var i = 0; i < varyingCount; i++) {
  53680. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  53681. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  53682. }
  53683. var depCount = 0;
  53684. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  53685. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  53686. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  53687. depCount++;
  53688. }
  53689. if (this.packedFloat) {
  53690. defines += "#define PACKEDFLOAT 1";
  53691. }
  53692. this.updateEffect(defines, null, null, {
  53693. varyingCount: varyingCount,
  53694. depCount: depCount
  53695. });
  53696. };
  53697. /**
  53698. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  53699. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  53700. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  53701. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  53702. * The gaps between physical kernels are compensated for in the weighting of the samples
  53703. * @param idealKernel Ideal blur kernel.
  53704. * @return Nearest best kernel.
  53705. */
  53706. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  53707. var v = Math.round(idealKernel);
  53708. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  53709. var k = _a[_i];
  53710. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  53711. return Math.max(k, 3);
  53712. }
  53713. }
  53714. return Math.max(v, 3);
  53715. };
  53716. /**
  53717. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  53718. * @param x The point on the Gaussian distribution to sample.
  53719. * @return the value of the Gaussian function at x.
  53720. */
  53721. BlurPostProcess.prototype._gaussianWeight = function (x) {
  53722. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  53723. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  53724. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  53725. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  53726. // truncated at around 1.3% of peak strength.
  53727. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  53728. var sigma = (1 / 3);
  53729. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  53730. var exponent = -((x * x) / (2.0 * sigma * sigma));
  53731. var weight = (1.0 / denominator) * Math.exp(exponent);
  53732. return weight;
  53733. };
  53734. /**
  53735. * Generates a string that can be used as a floating point number in GLSL.
  53736. * @param x Value to print.
  53737. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  53738. * @return GLSL float string.
  53739. */
  53740. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  53741. if (decimalFigures === void 0) { decimalFigures = 8; }
  53742. return x.toFixed(decimalFigures).replace(/0+$/, '');
  53743. };
  53744. return BlurPostProcess;
  53745. }(BABYLON.PostProcess));
  53746. BABYLON.BlurPostProcess = BlurPostProcess;
  53747. })(BABYLON || (BABYLON = {}));
  53748. //# sourceMappingURL=babylon.blurPostProcess.js.map
  53749. /// <reference path="..\babylon.node.ts" />
  53750. var BABYLON;
  53751. (function (BABYLON) {
  53752. var Bone = (function (_super) {
  53753. __extends(Bone, _super);
  53754. function Bone(name, skeleton, parentBone, matrix, restPose) {
  53755. if (parentBone === void 0) { parentBone = null; }
  53756. var _this = _super.call(this, name, skeleton.getScene()) || this;
  53757. _this.name = name;
  53758. _this.children = new Array();
  53759. _this.animations = new Array();
  53760. _this._worldTransform = new BABYLON.Matrix();
  53761. _this._absoluteTransform = new BABYLON.Matrix();
  53762. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  53763. _this._scaleMatrix = BABYLON.Matrix.Identity();
  53764. _this._scaleVector = BABYLON.Vector3.One();
  53765. _this._negateScaleChildren = BABYLON.Vector3.One();
  53766. _this._scalingDeterminant = 1;
  53767. _this._skeleton = skeleton;
  53768. _this._localMatrix = matrix ? matrix : BABYLON.Matrix.Identity();
  53769. _this._baseMatrix = _this._localMatrix.clone();
  53770. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  53771. skeleton.bones.push(_this);
  53772. _this.setParent(parentBone, false);
  53773. _this._updateDifferenceMatrix();
  53774. return _this;
  53775. }
  53776. Object.defineProperty(Bone.prototype, "_matrix", {
  53777. get: function () {
  53778. return this._localMatrix;
  53779. },
  53780. set: function (val) {
  53781. if (this._localMatrix) {
  53782. this._localMatrix.copyFrom(val);
  53783. }
  53784. else {
  53785. this._localMatrix = val;
  53786. }
  53787. },
  53788. enumerable: true,
  53789. configurable: true
  53790. });
  53791. // Members
  53792. Bone.prototype.getSkeleton = function () {
  53793. return this._skeleton;
  53794. };
  53795. Bone.prototype.getParent = function () {
  53796. return this._parent;
  53797. };
  53798. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  53799. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  53800. if (this._parent === parent) {
  53801. return;
  53802. }
  53803. if (this._parent) {
  53804. var index = this._parent.children.indexOf(this);
  53805. if (index !== -1) {
  53806. this._parent.children.splice(index);
  53807. }
  53808. }
  53809. this._parent = parent;
  53810. if (this._parent) {
  53811. this._parent.children.push(this);
  53812. }
  53813. if (updateDifferenceMatrix) {
  53814. this._updateDifferenceMatrix();
  53815. }
  53816. };
  53817. Bone.prototype.getLocalMatrix = function () {
  53818. return this._localMatrix;
  53819. };
  53820. Bone.prototype.getBaseMatrix = function () {
  53821. return this._baseMatrix;
  53822. };
  53823. Bone.prototype.getRestPose = function () {
  53824. return this._restPose;
  53825. };
  53826. Bone.prototype.returnToRest = function () {
  53827. this.updateMatrix(this._restPose.clone());
  53828. };
  53829. Bone.prototype.getWorldMatrix = function () {
  53830. return this._worldTransform;
  53831. };
  53832. Bone.prototype.getInvertedAbsoluteTransform = function () {
  53833. return this._invertedAbsoluteTransform;
  53834. };
  53835. Bone.prototype.getAbsoluteTransform = function () {
  53836. return this._absoluteTransform;
  53837. };
  53838. Object.defineProperty(Bone.prototype, "position", {
  53839. // Properties (matches AbstractMesh properties)
  53840. get: function () {
  53841. return this.getPosition();
  53842. },
  53843. set: function (newPosition) {
  53844. this.setPosition(newPosition);
  53845. },
  53846. enumerable: true,
  53847. configurable: true
  53848. });
  53849. Object.defineProperty(Bone.prototype, "rotation", {
  53850. get: function () {
  53851. return this.getRotation();
  53852. },
  53853. set: function (newRotation) {
  53854. this.setRotation(newRotation);
  53855. },
  53856. enumerable: true,
  53857. configurable: true
  53858. });
  53859. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  53860. get: function () {
  53861. return this.getRotationQuaternion();
  53862. },
  53863. set: function (newRotation) {
  53864. this.setRotationQuaternion(newRotation);
  53865. },
  53866. enumerable: true,
  53867. configurable: true
  53868. });
  53869. Object.defineProperty(Bone.prototype, "scaling", {
  53870. get: function () {
  53871. return this.getScale();
  53872. },
  53873. set: function (newScaling) {
  53874. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  53875. },
  53876. enumerable: true,
  53877. configurable: true
  53878. });
  53879. // Methods
  53880. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  53881. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  53882. this._baseMatrix = matrix.clone();
  53883. this._localMatrix = matrix.clone();
  53884. this._skeleton._markAsDirty();
  53885. if (updateDifferenceMatrix) {
  53886. this._updateDifferenceMatrix();
  53887. }
  53888. };
  53889. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  53890. if (!rootMatrix) {
  53891. rootMatrix = this._baseMatrix;
  53892. }
  53893. if (this._parent) {
  53894. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  53895. }
  53896. else {
  53897. this._absoluteTransform.copyFrom(rootMatrix);
  53898. }
  53899. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  53900. for (var index = 0; index < this.children.length; index++) {
  53901. this.children[index]._updateDifferenceMatrix();
  53902. }
  53903. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  53904. };
  53905. Bone.prototype.markAsDirty = function () {
  53906. this._currentRenderId++;
  53907. this._skeleton._markAsDirty();
  53908. };
  53909. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  53910. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  53911. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  53912. // all animation may be coming from a library skeleton, so may need to create animation
  53913. if (this.animations.length === 0) {
  53914. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  53915. this.animations[0].setKeys([]);
  53916. }
  53917. // get animation info / verify there is such a range from the source bone
  53918. var sourceRange = source.animations[0].getRange(rangeName);
  53919. if (!sourceRange) {
  53920. return false;
  53921. }
  53922. var from = sourceRange.from;
  53923. var to = sourceRange.to;
  53924. var sourceKeys = source.animations[0].getKeys();
  53925. // rescaling prep
  53926. var sourceBoneLength = source.length;
  53927. var sourceParent = source.getParent();
  53928. var parent = this.getParent();
  53929. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  53930. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  53931. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  53932. var destKeys = this.animations[0].getKeys();
  53933. // loop vars declaration
  53934. var orig;
  53935. var origTranslation;
  53936. var mat;
  53937. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  53938. orig = sourceKeys[key];
  53939. if (orig.frame >= from && orig.frame <= to) {
  53940. if (rescaleAsRequired) {
  53941. mat = orig.value.clone();
  53942. // scale based on parent ratio, when bone has parent
  53943. if (parentScalingReqd) {
  53944. origTranslation = mat.getTranslation();
  53945. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  53946. // scale based on skeleton dimension ratio when root bone, and value is passed
  53947. }
  53948. else if (dimensionsScalingReqd) {
  53949. origTranslation = mat.getTranslation();
  53950. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  53951. // use original when root bone, and no data for skelDimensionsRatio
  53952. }
  53953. else {
  53954. mat = orig.value;
  53955. }
  53956. }
  53957. else {
  53958. mat = orig.value;
  53959. }
  53960. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  53961. }
  53962. }
  53963. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  53964. return true;
  53965. };
  53966. /**
  53967. * Translate the bone in local or world space.
  53968. * @param vec The amount to translate the bone.
  53969. * @param space The space that the translation is in.
  53970. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53971. */
  53972. Bone.prototype.translate = function (vec, space, mesh) {
  53973. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53974. var lm = this.getLocalMatrix();
  53975. if (space == BABYLON.Space.LOCAL) {
  53976. lm.m[12] += vec.x;
  53977. lm.m[13] += vec.y;
  53978. lm.m[14] += vec.z;
  53979. }
  53980. else {
  53981. var wm;
  53982. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53983. if (mesh) {
  53984. wm = mesh.getWorldMatrix();
  53985. }
  53986. this._skeleton.computeAbsoluteTransforms();
  53987. var tmat = Bone._tmpMats[0];
  53988. var tvec = Bone._tmpVecs[0];
  53989. if (mesh) {
  53990. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53991. tmat.multiplyToRef(wm, tmat);
  53992. }
  53993. else {
  53994. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53995. }
  53996. tmat.m[12] = 0;
  53997. tmat.m[13] = 0;
  53998. tmat.m[14] = 0;
  53999. tmat.invert();
  54000. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  54001. lm.m[12] += tvec.x;
  54002. lm.m[13] += tvec.y;
  54003. lm.m[14] += tvec.z;
  54004. }
  54005. this.markAsDirty();
  54006. };
  54007. /**
  54008. * Set the postion of the bone in local or world space.
  54009. * @param position The position to set the bone.
  54010. * @param space The space that the position is in.
  54011. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54012. */
  54013. Bone.prototype.setPosition = function (position, space, mesh) {
  54014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54015. var lm = this.getLocalMatrix();
  54016. if (space == BABYLON.Space.LOCAL) {
  54017. lm.m[12] = position.x;
  54018. lm.m[13] = position.y;
  54019. lm.m[14] = position.z;
  54020. }
  54021. else {
  54022. var wm;
  54023. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  54024. if (mesh) {
  54025. wm = mesh.getWorldMatrix();
  54026. }
  54027. this._skeleton.computeAbsoluteTransforms();
  54028. var tmat = Bone._tmpMats[0];
  54029. var vec = Bone._tmpVecs[0];
  54030. if (mesh) {
  54031. tmat.copyFrom(this._parent.getAbsoluteTransform());
  54032. tmat.multiplyToRef(wm, tmat);
  54033. }
  54034. else {
  54035. tmat.copyFrom(this._parent.getAbsoluteTransform());
  54036. }
  54037. tmat.invert();
  54038. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  54039. lm.m[12] = vec.x;
  54040. lm.m[13] = vec.y;
  54041. lm.m[14] = vec.z;
  54042. }
  54043. this.markAsDirty();
  54044. };
  54045. /**
  54046. * Set the absolute postion of the bone (world space).
  54047. * @param position The position to set the bone.
  54048. * @param mesh The mesh that this bone is attached to.
  54049. */
  54050. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  54051. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  54052. };
  54053. /**
  54054. * Set the scale of the bone on the x, y and z axes.
  54055. * @param x The scale of the bone on the x axis.
  54056. * @param x The scale of the bone on the y axis.
  54057. * @param z The scale of the bone on the z axis.
  54058. * @param scaleChildren Set this to true if children of the bone should be scaled.
  54059. */
  54060. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  54061. if (scaleChildren === void 0) { scaleChildren = false; }
  54062. if (this.animations[0] && !this.animations[0].isStopped()) {
  54063. if (!scaleChildren) {
  54064. this._negateScaleChildren.x = 1 / x;
  54065. this._negateScaleChildren.y = 1 / y;
  54066. this._negateScaleChildren.z = 1 / z;
  54067. }
  54068. this._syncScaleVector();
  54069. }
  54070. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  54071. };
  54072. /**
  54073. * Scale the bone on the x, y and z axes.
  54074. * @param x The amount to scale the bone on the x axis.
  54075. * @param x The amount to scale the bone on the y axis.
  54076. * @param z The amount to scale the bone on the z axis.
  54077. * @param scaleChildren Set this to true if children of the bone should be scaled.
  54078. */
  54079. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  54080. if (scaleChildren === void 0) { scaleChildren = false; }
  54081. var locMat = this.getLocalMatrix();
  54082. var origLocMat = Bone._tmpMats[0];
  54083. origLocMat.copyFrom(locMat);
  54084. var origLocMatInv = Bone._tmpMats[1];
  54085. origLocMatInv.copyFrom(origLocMat);
  54086. origLocMatInv.invert();
  54087. var scaleMat = Bone._tmpMats[2];
  54088. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  54089. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  54090. this._scaleVector.x *= x;
  54091. this._scaleVector.y *= y;
  54092. this._scaleVector.z *= z;
  54093. locMat.multiplyToRef(origLocMatInv, locMat);
  54094. locMat.multiplyToRef(scaleMat, locMat);
  54095. locMat.multiplyToRef(origLocMat, locMat);
  54096. var parent = this.getParent();
  54097. if (parent) {
  54098. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  54099. }
  54100. else {
  54101. this.getAbsoluteTransform().copyFrom(locMat);
  54102. }
  54103. var len = this.children.length;
  54104. scaleMat.invert();
  54105. for (var i = 0; i < len; i++) {
  54106. var child = this.children[i];
  54107. var cm = child.getLocalMatrix();
  54108. cm.multiplyToRef(scaleMat, cm);
  54109. var lm = child.getLocalMatrix();
  54110. lm.m[12] *= x;
  54111. lm.m[13] *= y;
  54112. lm.m[14] *= z;
  54113. }
  54114. this.computeAbsoluteTransforms();
  54115. if (scaleChildren) {
  54116. for (var i = 0; i < len; i++) {
  54117. this.children[i].scale(x, y, z, scaleChildren);
  54118. }
  54119. }
  54120. this.markAsDirty();
  54121. };
  54122. /**
  54123. * Set the yaw, pitch, and roll of the bone in local or world space.
  54124. * @param yaw The rotation of the bone on the y axis.
  54125. * @param pitch The rotation of the bone on the x axis.
  54126. * @param roll The rotation of the bone on the z axis.
  54127. * @param space The space that the axes of rotation are in.
  54128. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54129. */
  54130. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  54131. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54132. var rotMat = Bone._tmpMats[0];
  54133. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  54134. var rotMatInv = Bone._tmpMats[1];
  54135. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54136. rotMatInv.multiplyToRef(rotMat, rotMat);
  54137. this._rotateWithMatrix(rotMat, space, mesh);
  54138. };
  54139. /**
  54140. * Rotate the bone on an axis in local or world space.
  54141. * @param axis The axis to rotate the bone on.
  54142. * @param amount The amount to rotate the bone.
  54143. * @param space The space that the axis is in.
  54144. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54145. */
  54146. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  54147. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54148. var rmat = Bone._tmpMats[0];
  54149. rmat.m[12] = 0;
  54150. rmat.m[13] = 0;
  54151. rmat.m[14] = 0;
  54152. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  54153. this._rotateWithMatrix(rmat, space, mesh);
  54154. };
  54155. /**
  54156. * Set the rotation of the bone to a particular axis angle in local or world space.
  54157. * @param axis The axis to rotate the bone on.
  54158. * @param angle The angle that the bone should be rotated to.
  54159. * @param space The space that the axis is in.
  54160. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54161. */
  54162. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  54163. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54164. var rotMat = Bone._tmpMats[0];
  54165. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  54166. var rotMatInv = Bone._tmpMats[1];
  54167. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54168. rotMatInv.multiplyToRef(rotMat, rotMat);
  54169. this._rotateWithMatrix(rotMat, space, mesh);
  54170. };
  54171. /**
  54172. * Set the euler rotation of the bone in local of world space.
  54173. * @param rotation The euler rotation that the bone should be set to.
  54174. * @param space The space that the rotation is in.
  54175. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54176. */
  54177. Bone.prototype.setRotation = function (rotation, space, mesh) {
  54178. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54179. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  54180. };
  54181. /**
  54182. * Set the quaternion rotation of the bone in local of world space.
  54183. * @param quat The quaternion rotation that the bone should be set to.
  54184. * @param space The space that the rotation is in.
  54185. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54186. */
  54187. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  54188. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54189. var rotMatInv = Bone._tmpMats[0];
  54190. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54191. var rotMat = Bone._tmpMats[1];
  54192. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  54193. rotMatInv.multiplyToRef(rotMat, rotMat);
  54194. this._rotateWithMatrix(rotMat, space, mesh);
  54195. };
  54196. /**
  54197. * Set the rotation matrix of the bone in local of world space.
  54198. * @param rotMat The rotation matrix that the bone should be set to.
  54199. * @param space The space that the rotation is in.
  54200. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54201. */
  54202. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  54203. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54204. var rotMatInv = Bone._tmpMats[0];
  54205. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54206. var rotMat2 = Bone._tmpMats[1];
  54207. rotMat2.copyFrom(rotMat);
  54208. rotMatInv.multiplyToRef(rotMat, rotMat2);
  54209. this._rotateWithMatrix(rotMat2, space, mesh);
  54210. };
  54211. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  54212. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54213. var lmat = this.getLocalMatrix();
  54214. var lx = lmat.m[12];
  54215. var ly = lmat.m[13];
  54216. var lz = lmat.m[14];
  54217. var parent = this.getParent();
  54218. var parentScale = Bone._tmpMats[3];
  54219. var parentScaleInv = Bone._tmpMats[4];
  54220. if (parent) {
  54221. if (space == BABYLON.Space.WORLD) {
  54222. if (mesh) {
  54223. parentScale.copyFrom(mesh.getWorldMatrix());
  54224. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  54225. }
  54226. else {
  54227. parentScale.copyFrom(parent.getAbsoluteTransform());
  54228. }
  54229. }
  54230. else {
  54231. parentScale = parent._scaleMatrix;
  54232. }
  54233. parentScaleInv.copyFrom(parentScale);
  54234. parentScaleInv.invert();
  54235. lmat.multiplyToRef(parentScale, lmat);
  54236. lmat.multiplyToRef(rmat, lmat);
  54237. lmat.multiplyToRef(parentScaleInv, lmat);
  54238. }
  54239. else {
  54240. if (space == BABYLON.Space.WORLD && mesh) {
  54241. parentScale.copyFrom(mesh.getWorldMatrix());
  54242. parentScaleInv.copyFrom(parentScale);
  54243. parentScaleInv.invert();
  54244. lmat.multiplyToRef(parentScale, lmat);
  54245. lmat.multiplyToRef(rmat, lmat);
  54246. lmat.multiplyToRef(parentScaleInv, lmat);
  54247. }
  54248. else {
  54249. lmat.multiplyToRef(rmat, lmat);
  54250. }
  54251. }
  54252. lmat.m[12] = lx;
  54253. lmat.m[13] = ly;
  54254. lmat.m[14] = lz;
  54255. this.computeAbsoluteTransforms();
  54256. this.markAsDirty();
  54257. };
  54258. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  54259. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54260. if (space == BABYLON.Space.WORLD) {
  54261. var scaleMatrix = Bone._tmpMats[2];
  54262. scaleMatrix.copyFrom(this._scaleMatrix);
  54263. rotMatInv.copyFrom(this.getAbsoluteTransform());
  54264. if (mesh) {
  54265. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  54266. var meshScale = Bone._tmpMats[3];
  54267. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  54268. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  54269. }
  54270. rotMatInv.invert();
  54271. scaleMatrix.m[0] *= this._scalingDeterminant;
  54272. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  54273. }
  54274. else {
  54275. rotMatInv.copyFrom(this.getLocalMatrix());
  54276. rotMatInv.invert();
  54277. var scaleMatrix = Bone._tmpMats[2];
  54278. scaleMatrix.copyFrom(this._scaleMatrix);
  54279. if (this._parent) {
  54280. var pscaleMatrix = Bone._tmpMats[3];
  54281. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  54282. pscaleMatrix.invert();
  54283. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  54284. }
  54285. else {
  54286. scaleMatrix.m[0] *= this._scalingDeterminant;
  54287. }
  54288. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  54289. }
  54290. };
  54291. /**
  54292. * Get the scale of the bone
  54293. * @returns the scale of the bone
  54294. */
  54295. Bone.prototype.getScale = function () {
  54296. return this._scaleVector.clone();
  54297. };
  54298. /**
  54299. * Copy the scale of the bone to a vector3.
  54300. * @param result The vector3 to copy the scale to
  54301. */
  54302. Bone.prototype.getScaleToRef = function (result) {
  54303. result.copyFrom(this._scaleVector);
  54304. };
  54305. /**
  54306. * Get the position of the bone in local or world space.
  54307. * @param space The space that the returned position is in.
  54308. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54309. * @returns The position of the bone
  54310. */
  54311. Bone.prototype.getPosition = function (space, mesh) {
  54312. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54313. var pos = BABYLON.Vector3.Zero();
  54314. this.getPositionToRef(space, mesh, pos);
  54315. return pos;
  54316. };
  54317. /**
  54318. * Copy the position of the bone to a vector3 in local or world space.
  54319. * @param space The space that the returned position is in.
  54320. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54321. * @param result The vector3 to copy the position to.
  54322. */
  54323. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  54324. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54325. if (space == BABYLON.Space.LOCAL) {
  54326. var lm = this.getLocalMatrix();
  54327. result.x = lm.m[12];
  54328. result.y = lm.m[13];
  54329. result.z = lm.m[14];
  54330. }
  54331. else {
  54332. var wm;
  54333. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  54334. if (mesh) {
  54335. wm = mesh.getWorldMatrix();
  54336. }
  54337. this._skeleton.computeAbsoluteTransforms();
  54338. var tmat = Bone._tmpMats[0];
  54339. if (mesh) {
  54340. tmat.copyFrom(this.getAbsoluteTransform());
  54341. tmat.multiplyToRef(wm, tmat);
  54342. }
  54343. else {
  54344. tmat = this.getAbsoluteTransform();
  54345. }
  54346. result.x = tmat.m[12];
  54347. result.y = tmat.m[13];
  54348. result.z = tmat.m[14];
  54349. }
  54350. };
  54351. /**
  54352. * Get the absolute position of the bone (world space).
  54353. * @param mesh The mesh that this bone is attached to.
  54354. * @returns The absolute position of the bone
  54355. */
  54356. Bone.prototype.getAbsolutePosition = function (mesh) {
  54357. var pos = BABYLON.Vector3.Zero();
  54358. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  54359. return pos;
  54360. };
  54361. /**
  54362. * Copy the absolute position of the bone (world space) to the result param.
  54363. * @param mesh The mesh that this bone is attached to.
  54364. * @param result The vector3 to copy the absolute position to.
  54365. */
  54366. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  54367. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  54368. };
  54369. /**
  54370. * Compute the absolute transforms of this bone and its children.
  54371. */
  54372. Bone.prototype.computeAbsoluteTransforms = function () {
  54373. if (this._parent) {
  54374. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  54375. }
  54376. else {
  54377. this._absoluteTransform.copyFrom(this._localMatrix);
  54378. var poseMatrix = this._skeleton.getPoseMatrix();
  54379. if (poseMatrix) {
  54380. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  54381. }
  54382. }
  54383. var children = this.children;
  54384. var len = children.length;
  54385. for (var i = 0; i < len; i++) {
  54386. children[i].computeAbsoluteTransforms();
  54387. }
  54388. };
  54389. Bone.prototype._syncScaleVector = function () {
  54390. var lm = this.getLocalMatrix();
  54391. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  54392. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  54393. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  54394. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  54395. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  54396. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  54397. this._scaleVector.x = xs * Math.sqrt(xsq);
  54398. this._scaleVector.y = ys * Math.sqrt(ysq);
  54399. this._scaleVector.z = zs * Math.sqrt(zsq);
  54400. if (this._parent) {
  54401. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  54402. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  54403. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  54404. }
  54405. 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);
  54406. };
  54407. /**
  54408. * Get the world direction from an axis that is in the local space of the bone.
  54409. * @param localAxis The local direction that is used to compute the world direction.
  54410. * @param mesh The mesh that this bone is attached to.
  54411. * @returns The world direction
  54412. */
  54413. Bone.prototype.getDirection = function (localAxis, mesh) {
  54414. var result = BABYLON.Vector3.Zero();
  54415. this.getDirectionToRef(localAxis, mesh, result);
  54416. return result;
  54417. };
  54418. /**
  54419. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  54420. * @param localAxis The local direction that is used to compute the world direction.
  54421. * @param mesh The mesh that this bone is attached to.
  54422. * @param result The vector3 that the world direction will be copied to.
  54423. */
  54424. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  54425. var wm;
  54426. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  54427. if (mesh) {
  54428. wm = mesh.getWorldMatrix();
  54429. }
  54430. this._skeleton.computeAbsoluteTransforms();
  54431. var mat = Bone._tmpMats[0];
  54432. mat.copyFrom(this.getAbsoluteTransform());
  54433. if (mesh) {
  54434. mat.multiplyToRef(wm, mat);
  54435. }
  54436. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  54437. result.normalize();
  54438. };
  54439. /**
  54440. * Get the euler rotation of the bone in local or world space.
  54441. * @param space The space that the rotation should be in.
  54442. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54443. * @returns The euler rotation
  54444. */
  54445. Bone.prototype.getRotation = function (space, mesh) {
  54446. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54447. var result = BABYLON.Vector3.Zero();
  54448. this.getRotationToRef(space, mesh, result);
  54449. return result;
  54450. };
  54451. /**
  54452. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  54453. * @param space The space that the rotation should be in.
  54454. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54455. * @param result The vector3 that the rotation should be copied to.
  54456. */
  54457. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  54458. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54459. var quat = Bone._tmpQuat;
  54460. this.getRotationQuaternionToRef(space, mesh, quat);
  54461. quat.toEulerAnglesToRef(result);
  54462. };
  54463. /**
  54464. * Get the quaternion rotation of the bone in either local or world space.
  54465. * @param space The space that the rotation should be in.
  54466. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54467. * @returns The quaternion rotation
  54468. */
  54469. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  54470. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54471. var result = BABYLON.Quaternion.Identity();
  54472. this.getRotationQuaternionToRef(space, mesh, result);
  54473. return result;
  54474. };
  54475. /**
  54476. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  54477. * @param space The space that the rotation should be in.
  54478. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54479. * @param result The quaternion that the rotation should be copied to.
  54480. */
  54481. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  54482. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54483. if (space == BABYLON.Space.LOCAL) {
  54484. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  54485. }
  54486. else {
  54487. var mat = Bone._tmpMats[0];
  54488. var amat = this.getAbsoluteTransform();
  54489. if (mesh) {
  54490. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  54491. }
  54492. else {
  54493. mat.copyFrom(amat);
  54494. }
  54495. mat.m[0] *= this._scalingDeterminant;
  54496. mat.m[1] *= this._scalingDeterminant;
  54497. mat.m[2] *= this._scalingDeterminant;
  54498. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  54499. }
  54500. };
  54501. /**
  54502. * Get the rotation matrix of the bone in local or world space.
  54503. * @param space The space that the rotation should be in.
  54504. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54505. * @returns The rotation matrix
  54506. */
  54507. Bone.prototype.getRotationMatrix = function (space, mesh) {
  54508. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54509. var result = BABYLON.Matrix.Identity();
  54510. this.getRotationMatrixToRef(space, mesh, result);
  54511. return result;
  54512. };
  54513. /**
  54514. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  54515. * @param space The space that the rotation should be in.
  54516. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54517. * @param result The quaternion that the rotation should be copied to.
  54518. */
  54519. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  54520. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54521. if (space == BABYLON.Space.LOCAL) {
  54522. this.getLocalMatrix().getRotationMatrixToRef(result);
  54523. }
  54524. else {
  54525. var mat = Bone._tmpMats[0];
  54526. var amat = this.getAbsoluteTransform();
  54527. if (mesh) {
  54528. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  54529. }
  54530. else {
  54531. mat.copyFrom(amat);
  54532. }
  54533. mat.m[0] *= this._scalingDeterminant;
  54534. mat.m[1] *= this._scalingDeterminant;
  54535. mat.m[2] *= this._scalingDeterminant;
  54536. mat.getRotationMatrixToRef(result);
  54537. }
  54538. };
  54539. /**
  54540. * Get the world position of a point that is in the local space of the bone.
  54541. * @param position The local position
  54542. * @param mesh The mesh that this bone is attached to.
  54543. * @returns The world position
  54544. */
  54545. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  54546. var result = BABYLON.Vector3.Zero();
  54547. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  54548. return result;
  54549. };
  54550. /**
  54551. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  54552. * @param position The local position
  54553. * @param mesh The mesh that this bone is attached to.
  54554. * @param result The vector3 that the world position should be copied to.
  54555. */
  54556. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  54557. var wm;
  54558. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  54559. if (mesh) {
  54560. wm = mesh.getWorldMatrix();
  54561. }
  54562. this._skeleton.computeAbsoluteTransforms();
  54563. var tmat = Bone._tmpMats[0];
  54564. if (mesh) {
  54565. tmat.copyFrom(this.getAbsoluteTransform());
  54566. tmat.multiplyToRef(wm, tmat);
  54567. }
  54568. else {
  54569. tmat = this.getAbsoluteTransform();
  54570. }
  54571. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  54572. };
  54573. /**
  54574. * Get the local position of a point that is in world space.
  54575. * @param position The world position
  54576. * @param mesh The mesh that this bone is attached to.
  54577. * @returns The local position
  54578. */
  54579. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  54580. var result = BABYLON.Vector3.Zero();
  54581. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  54582. return result;
  54583. };
  54584. /**
  54585. * Get the local position of a point that is in world space and copy it to the result param.
  54586. * @param position The world position
  54587. * @param mesh The mesh that this bone is attached to.
  54588. * @param result The vector3 that the local position should be copied to.
  54589. */
  54590. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  54591. var wm;
  54592. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  54593. if (mesh) {
  54594. wm = mesh.getWorldMatrix();
  54595. }
  54596. this._skeleton.computeAbsoluteTransforms();
  54597. var tmat = Bone._tmpMats[0];
  54598. tmat.copyFrom(this.getAbsoluteTransform());
  54599. if (mesh) {
  54600. tmat.multiplyToRef(wm, tmat);
  54601. }
  54602. tmat.invert();
  54603. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  54604. };
  54605. return Bone;
  54606. }(BABYLON.Node));
  54607. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  54608. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  54609. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  54610. BABYLON.Bone = Bone;
  54611. })(BABYLON || (BABYLON = {}));
  54612. //# sourceMappingURL=babylon.bone.js.map
  54613. var BABYLON;
  54614. (function (BABYLON) {
  54615. var BoneIKController = (function () {
  54616. function BoneIKController(mesh, bone, options) {
  54617. this.targetPosition = BABYLON.Vector3.Zero();
  54618. this.poleTargetPosition = BABYLON.Vector3.Zero();
  54619. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  54620. this.poleAngle = 0;
  54621. this.slerpAmount = 1;
  54622. this._bone1Quat = BABYLON.Quaternion.Identity();
  54623. this._bone1Mat = BABYLON.Matrix.Identity();
  54624. this._bone2Ang = Math.PI;
  54625. this._maxAngle = Math.PI;
  54626. this._rightHandedSystem = false;
  54627. this._bendAxis = BABYLON.Vector3.Right();
  54628. this._slerping = false;
  54629. this._adjustRoll = 0;
  54630. this._bone2 = bone;
  54631. this._bone1 = bone.getParent();
  54632. this.mesh = mesh;
  54633. var bonePos = bone.getPosition();
  54634. if (bone.getAbsoluteTransform().determinant() > 0) {
  54635. this._rightHandedSystem = true;
  54636. this._bendAxis.x = 0;
  54637. this._bendAxis.y = 0;
  54638. this._bendAxis.z = -1;
  54639. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  54640. this._adjustRoll = Math.PI * .5;
  54641. this._bendAxis.z = 1;
  54642. }
  54643. }
  54644. if (this._bone1.length) {
  54645. var boneScale1 = this._bone1.getScale();
  54646. var boneScale2 = this._bone2.getScale();
  54647. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  54648. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  54649. }
  54650. else if (this._bone1.children[0]) {
  54651. mesh.computeWorldMatrix(true);
  54652. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  54653. var pos2 = this._bone2.getAbsolutePosition(mesh);
  54654. var pos3 = this._bone1.getAbsolutePosition(mesh);
  54655. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  54656. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  54657. }
  54658. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  54659. this.maxAngle = Math.PI;
  54660. if (options) {
  54661. if (options.targetMesh) {
  54662. this.targetMesh = options.targetMesh;
  54663. this.targetMesh.computeWorldMatrix(true);
  54664. }
  54665. if (options.poleTargetMesh) {
  54666. this.poleTargetMesh = options.poleTargetMesh;
  54667. this.poleTargetMesh.computeWorldMatrix(true);
  54668. }
  54669. else if (options.poleTargetBone) {
  54670. this.poleTargetBone = options.poleTargetBone;
  54671. }
  54672. else if (this._bone1.getParent()) {
  54673. this.poleTargetBone = this._bone1.getParent();
  54674. }
  54675. if (options.poleTargetLocalOffset) {
  54676. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  54677. }
  54678. if (options.poleAngle) {
  54679. this.poleAngle = options.poleAngle;
  54680. }
  54681. if (options.bendAxis) {
  54682. this._bendAxis.copyFrom(options.bendAxis);
  54683. }
  54684. if (options.maxAngle) {
  54685. this.maxAngle = options.maxAngle;
  54686. }
  54687. if (options.slerpAmount) {
  54688. this.slerpAmount = options.slerpAmount;
  54689. }
  54690. }
  54691. }
  54692. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  54693. get: function () {
  54694. return this._maxAngle;
  54695. },
  54696. set: function (value) {
  54697. this._setMaxAngle(value);
  54698. },
  54699. enumerable: true,
  54700. configurable: true
  54701. });
  54702. BoneIKController.prototype._setMaxAngle = function (ang) {
  54703. if (ang < 0) {
  54704. ang = 0;
  54705. }
  54706. if (ang > Math.PI || ang == undefined) {
  54707. ang = Math.PI;
  54708. }
  54709. this._maxAngle = ang;
  54710. var a = this._bone1Length;
  54711. var b = this._bone2Length;
  54712. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  54713. };
  54714. BoneIKController.prototype.update = function () {
  54715. var bone1 = this._bone1;
  54716. var target = this.targetPosition;
  54717. var poleTarget = this.poleTargetPosition;
  54718. var mat1 = BoneIKController._tmpMats[0];
  54719. var mat2 = BoneIKController._tmpMats[1];
  54720. if (this.targetMesh) {
  54721. target.copyFrom(this.targetMesh.getAbsolutePosition());
  54722. }
  54723. if (this.poleTargetBone) {
  54724. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  54725. }
  54726. else if (this.poleTargetMesh) {
  54727. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  54728. }
  54729. var bonePos = BoneIKController._tmpVecs[0];
  54730. var zaxis = BoneIKController._tmpVecs[1];
  54731. var xaxis = BoneIKController._tmpVecs[2];
  54732. var yaxis = BoneIKController._tmpVecs[3];
  54733. var upAxis = BoneIKController._tmpVecs[4];
  54734. var _tmpQuat = BoneIKController._tmpQuat;
  54735. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  54736. poleTarget.subtractToRef(bonePos, upAxis);
  54737. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  54738. upAxis.y = 1;
  54739. }
  54740. else {
  54741. upAxis.normalize();
  54742. }
  54743. target.subtractToRef(bonePos, yaxis);
  54744. yaxis.normalize();
  54745. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  54746. zaxis.normalize();
  54747. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  54748. xaxis.normalize();
  54749. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  54750. var a = this._bone1Length;
  54751. var b = this._bone2Length;
  54752. var c = BABYLON.Vector3.Distance(bonePos, target);
  54753. if (this._maxReach > 0) {
  54754. c = Math.min(this._maxReach, c);
  54755. }
  54756. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  54757. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  54758. if (acosa > 1) {
  54759. acosa = 1;
  54760. }
  54761. if (acosb > 1) {
  54762. acosb = 1;
  54763. }
  54764. if (acosa < -1) {
  54765. acosa = -1;
  54766. }
  54767. if (acosb < -1) {
  54768. acosb = -1;
  54769. }
  54770. var angA = Math.acos(acosa);
  54771. var angB = Math.acos(acosb);
  54772. var angC = -angA - angB;
  54773. if (this._rightHandedSystem) {
  54774. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  54775. mat2.multiplyToRef(mat1, mat1);
  54776. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  54777. mat2.multiplyToRef(mat1, mat1);
  54778. }
  54779. else {
  54780. var _tmpVec = BoneIKController._tmpVecs[5];
  54781. _tmpVec.copyFrom(this._bendAxis);
  54782. _tmpVec.x *= -1;
  54783. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  54784. mat2.multiplyToRef(mat1, mat1);
  54785. }
  54786. if (this.poleAngle) {
  54787. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  54788. mat1.multiplyToRef(mat2, mat1);
  54789. }
  54790. if (this.slerpAmount < 1) {
  54791. if (!this._slerping) {
  54792. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  54793. }
  54794. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  54795. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  54796. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  54797. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  54798. this._slerping = true;
  54799. }
  54800. else {
  54801. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  54802. this._bone1Mat.copyFrom(mat1);
  54803. this._slerping = false;
  54804. }
  54805. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  54806. this._bone2Ang = angC;
  54807. };
  54808. return BoneIKController;
  54809. }());
  54810. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  54811. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  54812. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  54813. BABYLON.BoneIKController = BoneIKController;
  54814. })(BABYLON || (BABYLON = {}));
  54815. //# sourceMappingURL=babylon.boneIKController.js.map
  54816. var BABYLON;
  54817. (function (BABYLON) {
  54818. var BoneLookController = (function () {
  54819. /**
  54820. * Create a BoneLookController
  54821. * @param mesh the mesh that the bone belongs to
  54822. * @param bone the bone that will be looking to the target
  54823. * @param target the target Vector3 to look at
  54824. * @param settings optional settings:
  54825. * - maxYaw: the maximum angle the bone will yaw to
  54826. * - minYaw: the minimum angle the bone will yaw to
  54827. * - maxPitch: the maximum angle the bone will pitch to
  54828. * - minPitch: the minimum angle the bone will yaw to
  54829. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  54830. * - upAxis: the up axis of the coordinate system
  54831. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  54832. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  54833. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  54834. * - adjustYaw: used to make an adjustment to the yaw of the bone
  54835. * - adjustPitch: used to make an adjustment to the pitch of the bone
  54836. * - adjustRoll: used to make an adjustment to the roll of the bone
  54837. **/
  54838. function BoneLookController(mesh, bone, target, options) {
  54839. /**
  54840. * The up axis of the coordinate system that is used when the bone is rotated.
  54841. */
  54842. this.upAxis = BABYLON.Vector3.Up();
  54843. /**
  54844. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  54845. */
  54846. this.upAxisSpace = BABYLON.Space.LOCAL;
  54847. /**
  54848. * Used to make an adjustment to the yaw of the bone.
  54849. */
  54850. this.adjustYaw = 0;
  54851. /**
  54852. * Used to make an adjustment to the pitch of the bone.
  54853. */
  54854. this.adjustPitch = 0;
  54855. /**
  54856. * Used to make an adjustment to the roll of the bone.
  54857. */
  54858. this.adjustRoll = 0;
  54859. /**
  54860. * 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).
  54861. */
  54862. this.slerpAmount = 1;
  54863. this._boneQuat = BABYLON.Quaternion.Identity();
  54864. this._slerping = false;
  54865. this._firstFrameSkipped = false;
  54866. this._fowardAxis = BABYLON.Vector3.Forward();
  54867. this.mesh = mesh;
  54868. this.bone = bone;
  54869. this.target = target;
  54870. if (options) {
  54871. if (options.adjustYaw) {
  54872. this.adjustYaw = options.adjustYaw;
  54873. }
  54874. if (options.adjustPitch) {
  54875. this.adjustPitch = options.adjustPitch;
  54876. }
  54877. if (options.adjustRoll) {
  54878. this.adjustRoll = options.adjustRoll;
  54879. }
  54880. if (options.maxYaw != null) {
  54881. this.maxYaw = options.maxYaw;
  54882. }
  54883. else {
  54884. this.maxYaw = Math.PI;
  54885. }
  54886. if (options.minYaw != null) {
  54887. this.minYaw = options.minYaw;
  54888. }
  54889. else {
  54890. this.minYaw = -Math.PI;
  54891. }
  54892. if (options.maxPitch != null) {
  54893. this.maxPitch = options.maxPitch;
  54894. }
  54895. else {
  54896. this.maxPitch = Math.PI;
  54897. }
  54898. if (options.minPitch != null) {
  54899. this.minPitch = options.minPitch;
  54900. }
  54901. else {
  54902. this.minPitch = -Math.PI;
  54903. }
  54904. if (options.slerpAmount != null) {
  54905. this.slerpAmount = options.slerpAmount;
  54906. }
  54907. if (options.upAxis != null) {
  54908. this.upAxis = options.upAxis;
  54909. }
  54910. if (options.upAxisSpace != null) {
  54911. this.upAxisSpace = options.upAxisSpace;
  54912. }
  54913. if (options.yawAxis != null || options.pitchAxis != null) {
  54914. var newYawAxis = BABYLON.Axis.Y;
  54915. var newPitchAxis = BABYLON.Axis.X;
  54916. if (options.yawAxis != null) {
  54917. newYawAxis = options.yawAxis.clone();
  54918. newYawAxis.normalize();
  54919. }
  54920. if (options.pitchAxis != null) {
  54921. newPitchAxis = options.pitchAxis.clone();
  54922. newPitchAxis.normalize();
  54923. }
  54924. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  54925. this._transformYawPitch = BABYLON.Matrix.Identity();
  54926. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  54927. this._transformYawPitchInv = this._transformYawPitch.clone();
  54928. this._transformYawPitch.invert();
  54929. }
  54930. }
  54931. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  54932. this.upAxisSpace = BABYLON.Space.LOCAL;
  54933. }
  54934. }
  54935. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  54936. /**
  54937. * Get/set the minimum yaw angle that the bone can look to.
  54938. */
  54939. get: function () {
  54940. return this._minYaw;
  54941. },
  54942. set: function (value) {
  54943. this._minYaw = value;
  54944. this._minYawSin = Math.sin(value);
  54945. this._minYawCos = Math.cos(value);
  54946. if (this._maxYaw != null) {
  54947. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  54948. this._yawRange = this._maxYaw - this._minYaw;
  54949. }
  54950. },
  54951. enumerable: true,
  54952. configurable: true
  54953. });
  54954. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  54955. /**
  54956. * Get/set the maximum yaw angle that the bone can look to.
  54957. */
  54958. get: function () {
  54959. return this._maxYaw;
  54960. },
  54961. set: function (value) {
  54962. this._maxYaw = value;
  54963. this._maxYawSin = Math.sin(value);
  54964. this._maxYawCos = Math.cos(value);
  54965. if (this._minYaw != null) {
  54966. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  54967. this._yawRange = this._maxYaw - this._minYaw;
  54968. }
  54969. },
  54970. enumerable: true,
  54971. configurable: true
  54972. });
  54973. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  54974. /**
  54975. * Get/set the minimum pitch angle that the bone can look to.
  54976. */
  54977. get: function () {
  54978. return this._minPitch;
  54979. },
  54980. set: function (value) {
  54981. this._minPitch = value;
  54982. this._minPitchTan = Math.tan(value);
  54983. },
  54984. enumerable: true,
  54985. configurable: true
  54986. });
  54987. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  54988. /**
  54989. * Get/set the maximum pitch angle that the bone can look to.
  54990. */
  54991. get: function () {
  54992. return this._maxPitch;
  54993. },
  54994. set: function (value) {
  54995. this._maxPitch = value;
  54996. this._maxPitchTan = Math.tan(value);
  54997. },
  54998. enumerable: true,
  54999. configurable: true
  55000. });
  55001. /**
  55002. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  55003. */
  55004. BoneLookController.prototype.update = function () {
  55005. //skip the first frame when slerping so that the mesh rotation is correct
  55006. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  55007. this._firstFrameSkipped = true;
  55008. return;
  55009. }
  55010. var bone = this.bone;
  55011. var bonePos = BoneLookController._tmpVecs[0];
  55012. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  55013. var target = this.target;
  55014. var _tmpMat1 = BoneLookController._tmpMats[0];
  55015. var _tmpMat2 = BoneLookController._tmpMats[1];
  55016. var mesh = this.mesh;
  55017. var parentBone = bone.getParent();
  55018. var upAxis = BoneLookController._tmpVecs[1];
  55019. upAxis.copyFrom(this.upAxis);
  55020. if (this.upAxisSpace == BABYLON.Space.BONE) {
  55021. if (this._transformYawPitch) {
  55022. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  55023. }
  55024. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  55025. }
  55026. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  55027. mesh.getDirectionToRef(upAxis, upAxis);
  55028. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  55029. upAxis.normalize();
  55030. }
  55031. }
  55032. var checkYaw = false;
  55033. var checkPitch = false;
  55034. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  55035. checkYaw = true;
  55036. }
  55037. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  55038. checkPitch = true;
  55039. }
  55040. if (checkYaw || checkPitch) {
  55041. var spaceMat = BoneLookController._tmpMats[2];
  55042. var spaceMatInv = BoneLookController._tmpMats[3];
  55043. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  55044. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  55045. }
  55046. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  55047. spaceMat.copyFrom(mesh.getWorldMatrix());
  55048. }
  55049. else {
  55050. var forwardAxis = BoneLookController._tmpVecs[2];
  55051. forwardAxis.copyFrom(this._fowardAxis);
  55052. if (this._transformYawPitch) {
  55053. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  55054. }
  55055. if (parentBone) {
  55056. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  55057. }
  55058. else {
  55059. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  55060. }
  55061. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  55062. rightAxis.normalize();
  55063. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  55064. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  55065. }
  55066. spaceMat.invertToRef(spaceMatInv);
  55067. var xzlen;
  55068. if (checkPitch) {
  55069. var localTarget = BoneLookController._tmpVecs[3];
  55070. target.subtractToRef(bonePos, localTarget);
  55071. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  55072. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  55073. var pitch = Math.atan2(localTarget.y, xzlen);
  55074. var newPitch = pitch;
  55075. if (pitch > this._maxPitch) {
  55076. localTarget.y = this._maxPitchTan * xzlen;
  55077. newPitch = this._maxPitch;
  55078. }
  55079. else if (pitch < this._minPitch) {
  55080. localTarget.y = this._minPitchTan * xzlen;
  55081. newPitch = this._minPitch;
  55082. }
  55083. if (pitch != newPitch) {
  55084. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  55085. localTarget.addInPlace(bonePos);
  55086. target = localTarget;
  55087. }
  55088. }
  55089. if (checkYaw) {
  55090. var localTarget = BoneLookController._tmpVecs[4];
  55091. target.subtractToRef(bonePos, localTarget);
  55092. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  55093. var yaw = Math.atan2(localTarget.x, localTarget.z);
  55094. var newYaw = yaw;
  55095. if (yaw > this._maxYaw || yaw < this._minYaw) {
  55096. if (xzlen == null) {
  55097. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  55098. }
  55099. if (this._yawRange > Math.PI) {
  55100. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  55101. localTarget.z = this._maxYawCos * xzlen;
  55102. localTarget.x = this._maxYawSin * xzlen;
  55103. newYaw = this._maxYaw;
  55104. }
  55105. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  55106. localTarget.z = this._minYawCos * xzlen;
  55107. localTarget.x = this._minYawSin * xzlen;
  55108. newYaw = this._minYaw;
  55109. }
  55110. }
  55111. else {
  55112. if (yaw > this._maxYaw) {
  55113. localTarget.z = this._maxYawCos * xzlen;
  55114. localTarget.x = this._maxYawSin * xzlen;
  55115. newYaw = this._maxYaw;
  55116. }
  55117. else if (yaw < this._minYaw) {
  55118. localTarget.z = this._minYawCos * xzlen;
  55119. localTarget.x = this._minYawSin * xzlen;
  55120. newYaw = this._minYaw;
  55121. }
  55122. }
  55123. }
  55124. if (this._slerping && this._yawRange > Math.PI) {
  55125. //are we going to be crossing into the min/max region?
  55126. var boneFwd = BoneLookController._tmpVecs[8];
  55127. boneFwd.copyFrom(BABYLON.Axis.Z);
  55128. if (this._transformYawPitch) {
  55129. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  55130. }
  55131. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  55132. this._boneQuat.toRotationMatrix(boneRotMat);
  55133. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  55134. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  55135. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  55136. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  55137. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  55138. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  55139. if (angBtwTar > angBtwMidYaw) {
  55140. if (xzlen == null) {
  55141. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  55142. }
  55143. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  55144. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  55145. if (angBtwMin < angBtwMax) {
  55146. newYaw = boneYaw + Math.PI * .75;
  55147. localTarget.z = Math.cos(newYaw) * xzlen;
  55148. localTarget.x = Math.sin(newYaw) * xzlen;
  55149. }
  55150. else {
  55151. newYaw = boneYaw - Math.PI * .75;
  55152. localTarget.z = Math.cos(newYaw) * xzlen;
  55153. localTarget.x = Math.sin(newYaw) * xzlen;
  55154. }
  55155. }
  55156. }
  55157. if (yaw != newYaw) {
  55158. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  55159. localTarget.addInPlace(bonePos);
  55160. target = localTarget;
  55161. }
  55162. }
  55163. }
  55164. var zaxis = BoneLookController._tmpVecs[5];
  55165. var xaxis = BoneLookController._tmpVecs[6];
  55166. var yaxis = BoneLookController._tmpVecs[7];
  55167. var _tmpQuat = BoneLookController._tmpQuat;
  55168. target.subtractToRef(bonePos, zaxis);
  55169. zaxis.normalize();
  55170. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  55171. xaxis.normalize();
  55172. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  55173. yaxis.normalize();
  55174. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  55175. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  55176. return;
  55177. }
  55178. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  55179. return;
  55180. }
  55181. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  55182. return;
  55183. }
  55184. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  55185. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  55186. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  55187. }
  55188. if (this.slerpAmount < 1) {
  55189. if (!this._slerping) {
  55190. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  55191. }
  55192. if (this._transformYawPitch) {
  55193. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  55194. }
  55195. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  55196. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  55197. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  55198. this._slerping = true;
  55199. }
  55200. else {
  55201. if (this._transformYawPitch) {
  55202. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  55203. }
  55204. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  55205. this._slerping = false;
  55206. }
  55207. };
  55208. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  55209. var angDiff = ang2 - ang1;
  55210. angDiff %= Math.PI * 2;
  55211. if (angDiff > Math.PI) {
  55212. angDiff -= Math.PI * 2;
  55213. }
  55214. else if (angDiff < -Math.PI) {
  55215. angDiff += Math.PI * 2;
  55216. }
  55217. return angDiff;
  55218. };
  55219. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  55220. ang1 %= (2 * Math.PI);
  55221. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  55222. ang2 %= (2 * Math.PI);
  55223. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  55224. var ab = 0;
  55225. if (ang1 < ang2) {
  55226. ab = ang2 - ang1;
  55227. }
  55228. else {
  55229. ab = ang1 - ang2;
  55230. }
  55231. if (ab > Math.PI) {
  55232. ab = Math.PI * 2 - ab;
  55233. }
  55234. return ab;
  55235. };
  55236. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  55237. ang %= (2 * Math.PI);
  55238. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  55239. ang1 %= (2 * Math.PI);
  55240. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  55241. ang2 %= (2 * Math.PI);
  55242. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  55243. if (ang1 < ang2) {
  55244. if (ang > ang1 && ang < ang2) {
  55245. return true;
  55246. }
  55247. }
  55248. else {
  55249. if (ang > ang2 && ang < ang1) {
  55250. return true;
  55251. }
  55252. }
  55253. return false;
  55254. };
  55255. return BoneLookController;
  55256. }());
  55257. 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()];
  55258. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  55259. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  55260. BABYLON.BoneLookController = BoneLookController;
  55261. })(BABYLON || (BABYLON = {}));
  55262. //# sourceMappingURL=babylon.boneLookController.js.map
  55263. var BABYLON;
  55264. (function (BABYLON) {
  55265. var Skeleton = (function () {
  55266. function Skeleton(name, id, scene) {
  55267. this.name = name;
  55268. this.id = id;
  55269. this.bones = new Array();
  55270. this.needInitialSkinMatrix = false;
  55271. this._isDirty = true;
  55272. this._meshesWithPoseMatrix = new Array();
  55273. this._identity = BABYLON.Matrix.Identity();
  55274. this._ranges = {};
  55275. this._lastAbsoluteTransformsUpdateId = -1;
  55276. // Events
  55277. /**
  55278. * An event triggered before computing the skeleton's matrices
  55279. * @type {BABYLON.Observable}
  55280. */
  55281. this.onBeforeComputeObservable = new BABYLON.Observable();
  55282. this.bones = [];
  55283. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55284. scene.skeletons.push(this);
  55285. //make sure it will recalculate the matrix next time prepare is called.
  55286. this._isDirty = true;
  55287. }
  55288. // Members
  55289. Skeleton.prototype.getTransformMatrices = function (mesh) {
  55290. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  55291. return mesh._bonesTransformMatrices;
  55292. }
  55293. if (!this._transformMatrices) {
  55294. this.prepare();
  55295. }
  55296. return this._transformMatrices;
  55297. };
  55298. Skeleton.prototype.getScene = function () {
  55299. return this._scene;
  55300. };
  55301. // Methods
  55302. /**
  55303. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  55304. */
  55305. Skeleton.prototype.toString = function (fullDetails) {
  55306. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  55307. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  55308. if (fullDetails) {
  55309. ret += ", Ranges: {";
  55310. var first = true;
  55311. for (var name_1 in this._ranges) {
  55312. if (first) {
  55313. ret += ", ";
  55314. first = false;
  55315. }
  55316. ret += name_1;
  55317. }
  55318. ret += "}";
  55319. }
  55320. return ret;
  55321. };
  55322. /**
  55323. * Get bone's index searching by name
  55324. * @param {string} name is bone's name to search for
  55325. * @return {number} Indice of the bone. Returns -1 if not found
  55326. */
  55327. Skeleton.prototype.getBoneIndexByName = function (name) {
  55328. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  55329. if (this.bones[boneIndex].name === name) {
  55330. return boneIndex;
  55331. }
  55332. }
  55333. return -1;
  55334. };
  55335. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  55336. // check name not already in use
  55337. if (!this._ranges[name]) {
  55338. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  55339. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  55340. if (this.bones[i].animations[0]) {
  55341. this.bones[i].animations[0].createRange(name, from, to);
  55342. }
  55343. }
  55344. }
  55345. };
  55346. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  55347. if (deleteFrames === void 0) { deleteFrames = true; }
  55348. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  55349. if (this.bones[i].animations[0]) {
  55350. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  55351. }
  55352. }
  55353. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  55354. };
  55355. Skeleton.prototype.getAnimationRange = function (name) {
  55356. return this._ranges[name];
  55357. };
  55358. /**
  55359. * Returns as an Array, all AnimationRanges defined on this skeleton
  55360. */
  55361. Skeleton.prototype.getAnimationRanges = function () {
  55362. var animationRanges = [];
  55363. var name;
  55364. var i = 0;
  55365. for (name in this._ranges) {
  55366. animationRanges[i] = this._ranges[name];
  55367. i++;
  55368. }
  55369. return animationRanges;
  55370. };
  55371. /**
  55372. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  55373. */
  55374. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  55375. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  55376. if (this._ranges[name] || !source.getAnimationRange(name)) {
  55377. return false;
  55378. }
  55379. var ret = true;
  55380. var frameOffset = this._getHighestAnimationFrame() + 1;
  55381. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  55382. var boneDict = {};
  55383. var sourceBones = source.bones;
  55384. var nBones;
  55385. var i;
  55386. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  55387. boneDict[sourceBones[i].name] = sourceBones[i];
  55388. }
  55389. if (this.bones.length !== sourceBones.length) {
  55390. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  55391. ret = false;
  55392. }
  55393. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  55394. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  55395. var boneName = this.bones[i].name;
  55396. var sourceBone = boneDict[boneName];
  55397. if (sourceBone) {
  55398. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  55399. }
  55400. else {
  55401. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  55402. ret = false;
  55403. }
  55404. }
  55405. // do not call createAnimationRange(), since it also is done to bones, which was already done
  55406. var range = source.getAnimationRange(name);
  55407. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  55408. return ret;
  55409. };
  55410. Skeleton.prototype.returnToRest = function () {
  55411. for (var index = 0; index < this.bones.length; index++) {
  55412. this.bones[index].returnToRest();
  55413. }
  55414. };
  55415. Skeleton.prototype._getHighestAnimationFrame = function () {
  55416. var ret = 0;
  55417. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  55418. if (this.bones[i].animations[0]) {
  55419. var highest = this.bones[i].animations[0].getHighestFrame();
  55420. if (ret < highest) {
  55421. ret = highest;
  55422. }
  55423. }
  55424. }
  55425. return ret;
  55426. };
  55427. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  55428. var range = this.getAnimationRange(name);
  55429. if (!range) {
  55430. return null;
  55431. }
  55432. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  55433. };
  55434. Skeleton.prototype._markAsDirty = function () {
  55435. this._isDirty = true;
  55436. };
  55437. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  55438. this._meshesWithPoseMatrix.push(mesh);
  55439. };
  55440. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  55441. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  55442. if (index > -1) {
  55443. this._meshesWithPoseMatrix.splice(index, 1);
  55444. }
  55445. };
  55446. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  55447. this.onBeforeComputeObservable.notifyObservers(this);
  55448. for (var index = 0; index < this.bones.length; index++) {
  55449. var bone = this.bones[index];
  55450. var parentBone = bone.getParent();
  55451. if (parentBone) {
  55452. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  55453. }
  55454. else {
  55455. if (initialSkinMatrix) {
  55456. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  55457. }
  55458. else {
  55459. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  55460. }
  55461. }
  55462. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  55463. }
  55464. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  55465. };
  55466. Skeleton.prototype.prepare = function () {
  55467. if (!this._isDirty) {
  55468. return;
  55469. }
  55470. if (this.needInitialSkinMatrix) {
  55471. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  55472. var mesh = this._meshesWithPoseMatrix[index];
  55473. var poseMatrix = mesh.getPoseMatrix();
  55474. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  55475. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  55476. }
  55477. if (this._synchronizedWithMesh !== mesh) {
  55478. this._synchronizedWithMesh = mesh;
  55479. // Prepare bones
  55480. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  55481. var bone = this.bones[boneIndex];
  55482. if (!bone.getParent()) {
  55483. var matrix = bone.getBaseMatrix();
  55484. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  55485. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  55486. }
  55487. }
  55488. }
  55489. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  55490. }
  55491. }
  55492. else {
  55493. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  55494. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  55495. }
  55496. this._computeTransformMatrices(this._transformMatrices, null);
  55497. }
  55498. this._isDirty = false;
  55499. this._scene._activeBones.addCount(this.bones.length, false);
  55500. };
  55501. Skeleton.prototype.getAnimatables = function () {
  55502. if (!this._animatables || this._animatables.length !== this.bones.length) {
  55503. this._animatables = [];
  55504. for (var index = 0; index < this.bones.length; index++) {
  55505. this._animatables.push(this.bones[index]);
  55506. }
  55507. }
  55508. return this._animatables;
  55509. };
  55510. Skeleton.prototype.clone = function (name, id) {
  55511. var result = new Skeleton(name, id || name, this._scene);
  55512. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  55513. for (var index = 0; index < this.bones.length; index++) {
  55514. var source = this.bones[index];
  55515. var parentBone = null;
  55516. if (source.getParent()) {
  55517. var parentIndex = this.bones.indexOf(source.getParent());
  55518. parentBone = result.bones[parentIndex];
  55519. }
  55520. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  55521. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  55522. }
  55523. if (this._ranges) {
  55524. result._ranges = {};
  55525. for (var rangeName in this._ranges) {
  55526. result._ranges[rangeName] = this._ranges[rangeName].clone();
  55527. }
  55528. }
  55529. this._isDirty = true;
  55530. return result;
  55531. };
  55532. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  55533. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  55534. this.bones.forEach(function (bone) {
  55535. bone.animations.forEach(function (animation) {
  55536. animation.enableBlending = true;
  55537. animation.blendingSpeed = blendingSpeed;
  55538. });
  55539. });
  55540. };
  55541. Skeleton.prototype.dispose = function () {
  55542. this._meshesWithPoseMatrix = [];
  55543. // Animations
  55544. this.getScene().stopAnimation(this);
  55545. // Remove from scene
  55546. this.getScene().removeSkeleton(this);
  55547. };
  55548. Skeleton.prototype.serialize = function () {
  55549. var serializationObject = {};
  55550. serializationObject.name = this.name;
  55551. serializationObject.id = this.id;
  55552. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  55553. serializationObject.bones = [];
  55554. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  55555. for (var index = 0; index < this.bones.length; index++) {
  55556. var bone = this.bones[index];
  55557. var serializedBone = {
  55558. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  55559. name: bone.name,
  55560. matrix: bone.getBaseMatrix().toArray(),
  55561. rest: bone.getRestPose().toArray()
  55562. };
  55563. serializationObject.bones.push(serializedBone);
  55564. if (bone.length) {
  55565. serializedBone.length = bone.length;
  55566. }
  55567. if (bone.animations && bone.animations.length > 0) {
  55568. serializedBone.animation = bone.animations[0].serialize();
  55569. }
  55570. serializationObject.ranges = [];
  55571. for (var name in this._ranges) {
  55572. var range = {};
  55573. range.name = name;
  55574. range.from = this._ranges[name].from;
  55575. range.to = this._ranges[name].to;
  55576. serializationObject.ranges.push(range);
  55577. }
  55578. }
  55579. return serializationObject;
  55580. };
  55581. Skeleton.Parse = function (parsedSkeleton, scene) {
  55582. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  55583. if (parsedSkeleton.dimensionsAtRest) {
  55584. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  55585. }
  55586. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  55587. var index;
  55588. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  55589. var parsedBone = parsedSkeleton.bones[index];
  55590. var parentBone = null;
  55591. if (parsedBone.parentBoneIndex > -1) {
  55592. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  55593. }
  55594. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  55595. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  55596. if (parsedBone.length) {
  55597. bone.length = parsedBone.length;
  55598. }
  55599. if (parsedBone.animation) {
  55600. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  55601. }
  55602. }
  55603. // placed after bones, so createAnimationRange can cascade down
  55604. if (parsedSkeleton.ranges) {
  55605. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  55606. var data = parsedSkeleton.ranges[index];
  55607. skeleton.createAnimationRange(data.name, data.from, data.to);
  55608. }
  55609. }
  55610. return skeleton;
  55611. };
  55612. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  55613. if (forceUpdate === void 0) { forceUpdate = false; }
  55614. var renderId = this._scene.getRenderId();
  55615. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  55616. this.bones[0].computeAbsoluteTransforms();
  55617. this._lastAbsoluteTransformsUpdateId = renderId;
  55618. }
  55619. };
  55620. Skeleton.prototype.getPoseMatrix = function () {
  55621. var poseMatrix;
  55622. if (this._meshesWithPoseMatrix.length > 0) {
  55623. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  55624. }
  55625. return poseMatrix;
  55626. };
  55627. return Skeleton;
  55628. }());
  55629. BABYLON.Skeleton = Skeleton;
  55630. })(BABYLON || (BABYLON = {}));
  55631. //# sourceMappingURL=babylon.skeleton.js.map
  55632. var BABYLON;
  55633. (function (BABYLON) {
  55634. var SphericalPolynomial = (function () {
  55635. function SphericalPolynomial() {
  55636. this.x = BABYLON.Vector3.Zero();
  55637. this.y = BABYLON.Vector3.Zero();
  55638. this.z = BABYLON.Vector3.Zero();
  55639. this.xx = BABYLON.Vector3.Zero();
  55640. this.yy = BABYLON.Vector3.Zero();
  55641. this.zz = BABYLON.Vector3.Zero();
  55642. this.xy = BABYLON.Vector3.Zero();
  55643. this.yz = BABYLON.Vector3.Zero();
  55644. this.zx = BABYLON.Vector3.Zero();
  55645. }
  55646. SphericalPolynomial.prototype.addAmbient = function (color) {
  55647. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  55648. this.xx = this.xx.add(colorVector);
  55649. this.yy = this.yy.add(colorVector);
  55650. this.zz = this.zz.add(colorVector);
  55651. };
  55652. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  55653. var result = new SphericalPolynomial();
  55654. result.x = harmonics.L11.scale(1.02333);
  55655. result.y = harmonics.L1_1.scale(1.02333);
  55656. result.z = harmonics.L10.scale(1.02333);
  55657. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  55658. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  55659. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  55660. result.yz = harmonics.L2_1.scale(0.858086);
  55661. result.zx = harmonics.L21.scale(0.858086);
  55662. result.xy = harmonics.L2_2.scale(0.858086);
  55663. result.scale(1.0 / Math.PI);
  55664. return result;
  55665. };
  55666. SphericalPolynomial.prototype.scale = function (scale) {
  55667. this.x = this.x.scale(scale);
  55668. this.y = this.y.scale(scale);
  55669. this.z = this.z.scale(scale);
  55670. this.xx = this.xx.scale(scale);
  55671. this.yy = this.yy.scale(scale);
  55672. this.zz = this.zz.scale(scale);
  55673. this.yz = this.yz.scale(scale);
  55674. this.zx = this.zx.scale(scale);
  55675. this.xy = this.xy.scale(scale);
  55676. };
  55677. return SphericalPolynomial;
  55678. }());
  55679. BABYLON.SphericalPolynomial = SphericalPolynomial;
  55680. var SphericalHarmonics = (function () {
  55681. function SphericalHarmonics() {
  55682. this.L00 = BABYLON.Vector3.Zero();
  55683. this.L1_1 = BABYLON.Vector3.Zero();
  55684. this.L10 = BABYLON.Vector3.Zero();
  55685. this.L11 = BABYLON.Vector3.Zero();
  55686. this.L2_2 = BABYLON.Vector3.Zero();
  55687. this.L2_1 = BABYLON.Vector3.Zero();
  55688. this.L20 = BABYLON.Vector3.Zero();
  55689. this.L21 = BABYLON.Vector3.Zero();
  55690. this.L22 = BABYLON.Vector3.Zero();
  55691. }
  55692. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  55693. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  55694. var c = colorVector.scale(deltaSolidAngle);
  55695. this.L00 = this.L00.add(c.scale(0.282095));
  55696. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  55697. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  55698. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  55699. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  55700. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  55701. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  55702. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  55703. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  55704. };
  55705. SphericalHarmonics.prototype.scale = function (scale) {
  55706. this.L00 = this.L00.scale(scale);
  55707. this.L1_1 = this.L1_1.scale(scale);
  55708. this.L10 = this.L10.scale(scale);
  55709. this.L11 = this.L11.scale(scale);
  55710. this.L2_2 = this.L2_2.scale(scale);
  55711. this.L2_1 = this.L2_1.scale(scale);
  55712. this.L20 = this.L20.scale(scale);
  55713. this.L21 = this.L21.scale(scale);
  55714. this.L22 = this.L22.scale(scale);
  55715. };
  55716. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  55717. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  55718. //
  55719. // E_lm = A_l * L_lm
  55720. //
  55721. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  55722. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  55723. // the scaling factors are given in equation 9.
  55724. // Constant (Band 0)
  55725. this.L00 = this.L00.scale(3.141593);
  55726. // Linear (Band 1)
  55727. this.L1_1 = this.L1_1.scale(2.094395);
  55728. this.L10 = this.L10.scale(2.094395);
  55729. this.L11 = this.L11.scale(2.094395);
  55730. // Quadratic (Band 2)
  55731. this.L2_2 = this.L2_2.scale(0.785398);
  55732. this.L2_1 = this.L2_1.scale(0.785398);
  55733. this.L20 = this.L20.scale(0.785398);
  55734. this.L21 = this.L21.scale(0.785398);
  55735. this.L22 = this.L22.scale(0.785398);
  55736. };
  55737. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  55738. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  55739. // L = (1/pi) * E * rho
  55740. //
  55741. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  55742. this.scale(1.0 / Math.PI);
  55743. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  55744. // (The pixel shader must apply albedo after texture fetches, etc).
  55745. };
  55746. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  55747. var result = new SphericalHarmonics();
  55748. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  55749. result.L1_1 = polynomial.y.scale(0.977204);
  55750. result.L10 = polynomial.z.scale(0.977204);
  55751. result.L11 = polynomial.x.scale(0.977204);
  55752. result.L2_2 = polynomial.xy.scale(1.16538);
  55753. result.L2_1 = polynomial.yz.scale(1.16538);
  55754. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  55755. result.L21 = polynomial.zx.scale(1.16538);
  55756. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  55757. result.scale(Math.PI);
  55758. return result;
  55759. };
  55760. return SphericalHarmonics;
  55761. }());
  55762. BABYLON.SphericalHarmonics = SphericalHarmonics;
  55763. })(BABYLON || (BABYLON = {}));
  55764. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  55765. var BABYLON;
  55766. (function (BABYLON) {
  55767. var Internals;
  55768. (function (Internals) {
  55769. var FileFaceOrientation = (function () {
  55770. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  55771. this.name = name;
  55772. this.worldAxisForNormal = worldAxisForNormal;
  55773. this.worldAxisForFileX = worldAxisForFileX;
  55774. this.worldAxisForFileY = worldAxisForFileY;
  55775. }
  55776. return FileFaceOrientation;
  55777. }());
  55778. ;
  55779. /**
  55780. * Helper class dealing with the extraction of spherical polynomial dataArray
  55781. * from a cube map.
  55782. */
  55783. var CubeMapToSphericalPolynomialTools = (function () {
  55784. function CubeMapToSphericalPolynomialTools() {
  55785. }
  55786. /**
  55787. * Converts a texture to the according Spherical Polynomial data.
  55788. * This extracts the first 3 orders only as they are the only one used in the lighting.
  55789. *
  55790. * @param texture The texture to extract the information from.
  55791. * @return The Spherical Polynomial data.
  55792. */
  55793. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  55794. if (!texture.isCube) {
  55795. // Only supports cube Textures currently.
  55796. return null;
  55797. }
  55798. var size = texture.getSize().width;
  55799. var right = texture.readPixels(0);
  55800. var left = texture.readPixels(1);
  55801. var up;
  55802. var down;
  55803. if (texture.isRenderTarget) {
  55804. up = texture.readPixels(3);
  55805. down = texture.readPixels(2);
  55806. }
  55807. else {
  55808. up = texture.readPixels(2);
  55809. down = texture.readPixels(3);
  55810. }
  55811. var front = texture.readPixels(4);
  55812. var back = texture.readPixels(5);
  55813. var gammaSpace = texture.gammaSpace;
  55814. // Always read as RGBA.
  55815. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  55816. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55817. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55818. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55819. }
  55820. var cubeInfo = {
  55821. size: size,
  55822. right: right,
  55823. left: left,
  55824. up: up,
  55825. down: down,
  55826. front: front,
  55827. back: back,
  55828. format: format,
  55829. type: type,
  55830. gammaSpace: gammaSpace,
  55831. };
  55832. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  55833. };
  55834. /**
  55835. * Converts a cubemap to the according Spherical Polynomial data.
  55836. * This extracts the first 3 orders only as they are the only one used in the lighting.
  55837. *
  55838. * @param cubeInfo The Cube map to extract the information from.
  55839. * @return The Spherical Polynomial data.
  55840. */
  55841. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  55842. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  55843. var totalSolidAngle = 0.0;
  55844. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  55845. var du = 2.0 / cubeInfo.size;
  55846. var dv = du;
  55847. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  55848. var minUV = du * 0.5 - 1.0;
  55849. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55850. var fileFace = this.FileFaces[faceIndex];
  55851. var dataArray = cubeInfo[fileFace.name];
  55852. var v = minUV;
  55853. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  55854. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  55855. // Because SP is still linear, so summation is fine in that basis.
  55856. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  55857. for (var y = 0; y < cubeInfo.size; y++) {
  55858. var u = minUV;
  55859. for (var x = 0; x < cubeInfo.size; x++) {
  55860. // World direction (not normalised)
  55861. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  55862. worldDirection.normalize();
  55863. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  55864. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  55865. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  55866. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  55867. // Handle Integer types.
  55868. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55869. r /= 255;
  55870. g /= 255;
  55871. b /= 255;
  55872. }
  55873. // Handle Gamma space textures.
  55874. if (cubeInfo.gammaSpace) {
  55875. r = Math.pow(BABYLON.MathTools.Clamp(r), BABYLON.ToLinearSpace);
  55876. g = Math.pow(BABYLON.MathTools.Clamp(g), BABYLON.ToLinearSpace);
  55877. b = Math.pow(BABYLON.MathTools.Clamp(b), BABYLON.ToLinearSpace);
  55878. }
  55879. var color = new BABYLON.Color3(r, g, b);
  55880. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55881. totalSolidAngle += deltaSolidAngle;
  55882. u += du;
  55883. }
  55884. v += dv;
  55885. }
  55886. }
  55887. // Solid angle for entire sphere is 4*pi
  55888. var sphereSolidAngle = 4.0 * Math.PI;
  55889. // Adjust the solid angle to allow for how many faces we processed.
  55890. var facesProcessed = 6.0;
  55891. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  55892. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  55893. // This is needed because the numerical integration over the cube uses a
  55894. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  55895. // and also to compensate for accumulative error due to float precision in the summation.
  55896. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  55897. sphericalHarmonics.scale(correctionFactor);
  55898. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  55899. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  55900. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  55901. };
  55902. return CubeMapToSphericalPolynomialTools;
  55903. }());
  55904. CubeMapToSphericalPolynomialTools.FileFaces = [
  55905. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  55906. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  55907. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  55908. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  55909. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  55910. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  55911. ];
  55912. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  55913. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55914. })(BABYLON || (BABYLON = {}));
  55915. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  55916. var BABYLON;
  55917. (function (BABYLON) {
  55918. var Internals;
  55919. (function (Internals) {
  55920. /**
  55921. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  55922. */
  55923. var PanoramaToCubeMapTools = (function () {
  55924. function PanoramaToCubeMapTools() {
  55925. }
  55926. /**
  55927. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  55928. *
  55929. * @param float32Array The source data.
  55930. * @param inputWidth The width of the input panorama.
  55931. * @param inputhHeight The height of the input panorama.
  55932. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  55933. * @return The cubemap data
  55934. */
  55935. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  55936. if (!float32Array) {
  55937. throw "ConvertPanoramaToCubemap: input cannot be null";
  55938. }
  55939. if (float32Array.length != inputWidth * inputHeight * 3) {
  55940. throw "ConvertPanoramaToCubemap: input size is wrong";
  55941. }
  55942. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  55943. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  55944. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  55945. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  55946. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  55947. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  55948. return {
  55949. front: textureFront,
  55950. back: textureBack,
  55951. left: textureLeft,
  55952. right: textureRight,
  55953. up: textureUp,
  55954. down: textureDown,
  55955. size: size,
  55956. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  55957. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  55958. gammaSpace: false,
  55959. };
  55960. };
  55961. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  55962. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  55963. var textureArray = new Float32Array(buffer);
  55964. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  55965. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  55966. var dy = 1 / texSize;
  55967. var fy = 0;
  55968. for (var y = 0; y < texSize; y++) {
  55969. var xv1 = faceData[0];
  55970. var xv2 = faceData[2];
  55971. for (var x = 0; x < texSize; x++) {
  55972. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  55973. v.normalize();
  55974. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  55975. // 3 channels per pixels
  55976. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  55977. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  55978. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  55979. xv1 = xv1.add(rotDX1);
  55980. xv2 = xv2.add(rotDX2);
  55981. }
  55982. fy += dy;
  55983. }
  55984. return textureArray;
  55985. };
  55986. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  55987. var theta = Math.atan2(vDir.z, vDir.x);
  55988. var phi = Math.acos(vDir.y);
  55989. while (theta < -Math.PI)
  55990. theta += 2 * Math.PI;
  55991. while (theta > Math.PI)
  55992. theta -= 2 * Math.PI;
  55993. var dx = theta / Math.PI;
  55994. var dy = phi / Math.PI;
  55995. // recenter.
  55996. dx = dx * 0.5 + 0.5;
  55997. var px = Math.round(dx * inputWidth);
  55998. if (px < 0)
  55999. px = 0;
  56000. else if (px >= inputWidth)
  56001. px = inputWidth - 1;
  56002. var py = Math.round(dy * inputHeight);
  56003. if (py < 0)
  56004. py = 0;
  56005. else if (py >= inputHeight)
  56006. py = inputHeight - 1;
  56007. var inputY = (inputHeight - py - 1);
  56008. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  56009. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  56010. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  56011. return {
  56012. r: r,
  56013. g: g,
  56014. b: b
  56015. };
  56016. };
  56017. return PanoramaToCubeMapTools;
  56018. }());
  56019. PanoramaToCubeMapTools.FACE_FRONT = [
  56020. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56021. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56022. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56023. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56024. ];
  56025. PanoramaToCubeMapTools.FACE_BACK = [
  56026. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56027. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56028. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56029. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56030. ];
  56031. PanoramaToCubeMapTools.FACE_RIGHT = [
  56032. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56033. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56034. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56035. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56036. ];
  56037. PanoramaToCubeMapTools.FACE_LEFT = [
  56038. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56039. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56040. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56041. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56042. ];
  56043. PanoramaToCubeMapTools.FACE_DOWN = [
  56044. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56045. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56046. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56047. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56048. ];
  56049. PanoramaToCubeMapTools.FACE_UP = [
  56050. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56051. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56052. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56053. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56054. ];
  56055. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56056. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56057. })(BABYLON || (BABYLON = {}));
  56058. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  56059. var BABYLON;
  56060. (function (BABYLON) {
  56061. var Internals;
  56062. (function (Internals) {
  56063. ;
  56064. /**
  56065. * This groups tools to convert HDR texture to native colors array.
  56066. */
  56067. var HDRTools = (function () {
  56068. function HDRTools() {
  56069. }
  56070. HDRTools.Ldexp = function (mantissa, exponent) {
  56071. if (exponent > 1023) {
  56072. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  56073. }
  56074. if (exponent < -1074) {
  56075. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  56076. }
  56077. return mantissa * Math.pow(2, exponent);
  56078. };
  56079. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  56080. if (exponent > 0) {
  56081. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  56082. float32array[index + 0] = red * exponent;
  56083. float32array[index + 1] = green * exponent;
  56084. float32array[index + 2] = blue * exponent;
  56085. }
  56086. else {
  56087. float32array[index + 0] = 0;
  56088. float32array[index + 1] = 0;
  56089. float32array[index + 2] = 0;
  56090. }
  56091. };
  56092. HDRTools.readStringLine = function (uint8array, startIndex) {
  56093. var line = "";
  56094. var character = "";
  56095. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  56096. character = String.fromCharCode(uint8array[i]);
  56097. if (character == "\n") {
  56098. break;
  56099. }
  56100. line += character;
  56101. }
  56102. return line;
  56103. };
  56104. /**
  56105. * Reads header information from an RGBE texture stored in a native array.
  56106. * More information on this format are available here:
  56107. * https://en.wikipedia.org/wiki/RGBE_image_format
  56108. *
  56109. * @param uint8array The binary file stored in native array.
  56110. * @return The header information.
  56111. */
  56112. HDRTools.RGBE_ReadHeader = function (uint8array) {
  56113. var height = 0;
  56114. var width = 0;
  56115. var line = this.readStringLine(uint8array, 0);
  56116. if (line[0] != '#' || line[1] != '?') {
  56117. throw "Bad HDR Format.";
  56118. }
  56119. var endOfHeader = false;
  56120. var findFormat = false;
  56121. var lineIndex = 0;
  56122. do {
  56123. lineIndex += (line.length + 1);
  56124. line = this.readStringLine(uint8array, lineIndex);
  56125. if (line == "FORMAT=32-bit_rle_rgbe") {
  56126. findFormat = true;
  56127. }
  56128. else if (line.length == 0) {
  56129. endOfHeader = true;
  56130. }
  56131. } while (!endOfHeader);
  56132. if (!findFormat) {
  56133. throw "HDR Bad header format, unsupported FORMAT";
  56134. }
  56135. lineIndex += (line.length + 1);
  56136. line = this.readStringLine(uint8array, lineIndex);
  56137. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  56138. var match = sizeRegexp.exec(line);
  56139. // TODO. Support +Y and -X if needed.
  56140. if (match.length < 3) {
  56141. throw "HDR Bad header format, no size";
  56142. }
  56143. width = parseInt(match[2]);
  56144. height = parseInt(match[1]);
  56145. if (width < 8 || width > 0x7fff) {
  56146. throw "HDR Bad header format, unsupported size";
  56147. }
  56148. lineIndex += (line.length + 1);
  56149. return {
  56150. height: height,
  56151. width: width,
  56152. dataPosition: lineIndex
  56153. };
  56154. };
  56155. /**
  56156. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  56157. * This RGBE texture needs to store the information as a panorama.
  56158. *
  56159. * More information on this format are available here:
  56160. * https://en.wikipedia.org/wiki/RGBE_image_format
  56161. *
  56162. * @param buffer The binary file stored in an array buffer.
  56163. * @param size The expected size of the extracted cubemap.
  56164. * @return The Cube Map information.
  56165. */
  56166. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  56167. var uint8array = new Uint8Array(buffer);
  56168. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  56169. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56170. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  56171. return cubeMapData;
  56172. };
  56173. /**
  56174. * Returns the pixels data extracted from an RGBE texture.
  56175. * This pixels will be stored left to right up to down in the R G B order in one array.
  56176. *
  56177. * More information on this format are available here:
  56178. * https://en.wikipedia.org/wiki/RGBE_image_format
  56179. *
  56180. * @param uint8array The binary file stored in an array buffer.
  56181. * @param hdrInfo The header information of the file.
  56182. * @return The pixels data in RGB right to left up to down order.
  56183. */
  56184. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  56185. // Keep for multi format supports.
  56186. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56187. };
  56188. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  56189. var num_scanlines = hdrInfo.height;
  56190. var scanline_width = hdrInfo.width;
  56191. var a, b, c, d, count;
  56192. var dataIndex = hdrInfo.dataPosition;
  56193. var index = 0, endIndex = 0, i = 0;
  56194. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  56195. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  56196. // 3 channels of 4 bytes per pixel in float.
  56197. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  56198. var resultArray = new Float32Array(resultBuffer);
  56199. // read in each successive scanline
  56200. while (num_scanlines > 0) {
  56201. a = uint8array[dataIndex++];
  56202. b = uint8array[dataIndex++];
  56203. c = uint8array[dataIndex++];
  56204. d = uint8array[dataIndex++];
  56205. if (a != 2 || b != 2 || (c & 0x80)) {
  56206. // this file is not run length encoded
  56207. throw "HDR Bad header format, not RLE";
  56208. }
  56209. if (((c << 8) | d) != scanline_width) {
  56210. throw "HDR Bad header format, wrong scan line width";
  56211. }
  56212. index = 0;
  56213. // read each of the four channels for the scanline into the buffer
  56214. for (i = 0; i < 4; i++) {
  56215. endIndex = (i + 1) * scanline_width;
  56216. while (index < endIndex) {
  56217. a = uint8array[dataIndex++];
  56218. b = uint8array[dataIndex++];
  56219. if (a > 128) {
  56220. // a run of the same value
  56221. count = a - 128;
  56222. if ((count == 0) || (count > endIndex - index)) {
  56223. throw "HDR Bad Format, bad scanline data (run)";
  56224. }
  56225. while (count-- > 0) {
  56226. scanLineArray[index++] = b;
  56227. }
  56228. }
  56229. else {
  56230. // a non-run
  56231. count = a;
  56232. if ((count == 0) || (count > endIndex - index)) {
  56233. throw "HDR Bad Format, bad scanline data (non-run)";
  56234. }
  56235. scanLineArray[index++] = b;
  56236. if (--count > 0) {
  56237. for (var j = 0; j < count; j++) {
  56238. scanLineArray[index++] = uint8array[dataIndex++];
  56239. }
  56240. }
  56241. }
  56242. }
  56243. }
  56244. // now convert data from buffer into floats
  56245. for (i = 0; i < scanline_width; i++) {
  56246. a = scanLineArray[i];
  56247. b = scanLineArray[i + scanline_width];
  56248. c = scanLineArray[i + 2 * scanline_width];
  56249. d = scanLineArray[i + 3 * scanline_width];
  56250. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  56251. }
  56252. num_scanlines--;
  56253. }
  56254. return resultArray;
  56255. };
  56256. return HDRTools;
  56257. }());
  56258. Internals.HDRTools = HDRTools;
  56259. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56260. })(BABYLON || (BABYLON = {}));
  56261. //# sourceMappingURL=babylon.hdr.js.map
  56262. var BABYLON;
  56263. (function (BABYLON) {
  56264. /**
  56265. * This represents a texture coming from an HDR input.
  56266. *
  56267. * The only supported format is currently panorama picture stored in RGBE format.
  56268. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56269. */
  56270. var HDRCubeTexture = (function (_super) {
  56271. __extends(HDRCubeTexture, _super);
  56272. /**
  56273. * Instantiates an HDRTexture from the following parameters.
  56274. *
  56275. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56276. * @param scene The scene the texture will be used in
  56277. * @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.
  56278. * @param noMipmap Forces to not generate the mipmap if true
  56279. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56280. * @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)
  56281. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56282. */
  56283. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  56284. if (noMipmap === void 0) { noMipmap = false; }
  56285. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56286. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56287. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56288. if (onLoad === void 0) { onLoad = null; }
  56289. if (onError === void 0) { onError = null; }
  56290. var _this = _super.call(this, scene) || this;
  56291. _this._useInGammaSpace = false;
  56292. _this._generateHarmonics = true;
  56293. _this._isBABYLONPreprocessed = false;
  56294. _this._onLoad = null;
  56295. _this._onError = null;
  56296. /**
  56297. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56298. */
  56299. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56300. /**
  56301. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56302. * This is usefull at run time to apply the good shader.
  56303. */
  56304. _this.isPMREM = false;
  56305. _this._isBlocking = true;
  56306. if (!url) {
  56307. return _this;
  56308. }
  56309. _this.name = url;
  56310. _this.url = url;
  56311. _this.hasAlpha = false;
  56312. _this.isCube = true;
  56313. _this._textureMatrix = BABYLON.Matrix.Identity();
  56314. _this._onLoad = onLoad;
  56315. _this._onError = onError;
  56316. _this.gammaSpace = false;
  56317. if (size) {
  56318. _this._isBABYLONPreprocessed = false;
  56319. _this._noMipmap = noMipmap;
  56320. _this._size = size;
  56321. _this._useInGammaSpace = useInGammaSpace;
  56322. _this._usePMREMGenerator = usePMREMGenerator &&
  56323. scene.getEngine().getCaps().textureLOD &&
  56324. _this.getScene().getEngine().getCaps().textureFloat &&
  56325. !_this._useInGammaSpace;
  56326. }
  56327. else {
  56328. _this._isBABYLONPreprocessed = true;
  56329. _this._noMipmap = false;
  56330. _this._useInGammaSpace = false;
  56331. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56332. _this.getScene().getEngine().getCaps().textureFloat &&
  56333. !_this._useInGammaSpace;
  56334. }
  56335. _this.isPMREM = _this._usePMREMGenerator;
  56336. _this._texture = _this._getFromCache(url, _this._noMipmap);
  56337. if (!_this._texture) {
  56338. if (!scene.useDelayedTextureLoading) {
  56339. _this.loadTexture();
  56340. }
  56341. else {
  56342. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56343. }
  56344. }
  56345. return _this;
  56346. }
  56347. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  56348. /**
  56349. * Gets wether or not the texture is blocking during loading.
  56350. */
  56351. get: function () {
  56352. return this._isBlocking;
  56353. },
  56354. /**
  56355. * Sets wether or not the texture is blocking during loading.
  56356. */
  56357. set: function (value) {
  56358. this._isBlocking = value;
  56359. },
  56360. enumerable: true,
  56361. configurable: true
  56362. });
  56363. /**
  56364. * Occurs when the file is a preprocessed .babylon.hdr file.
  56365. */
  56366. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56367. var _this = this;
  56368. var mipLevels = 0;
  56369. var floatArrayView = null;
  56370. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56371. var mips = [];
  56372. var startIndex = 30;
  56373. for (var level = 0; level < mipLevels; level++) {
  56374. mips.push([]);
  56375. // Fill each pixel of the mip level.
  56376. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56377. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56378. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56379. mips[level].push(faceData);
  56380. startIndex += faceSize;
  56381. }
  56382. }
  56383. return mips;
  56384. } : null;
  56385. var callback = function (buffer) {
  56386. // Create Native Array Views
  56387. var intArrayView = new Int32Array(buffer);
  56388. floatArrayView = new Float32Array(buffer);
  56389. // Fill header.
  56390. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56391. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56392. // Update Texture Information.
  56393. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56394. // Fill polynomial information.
  56395. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56396. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56397. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56398. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56399. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56400. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56401. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56402. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56403. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56404. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56405. _this.sphericalPolynomial = sphericalPolynomial;
  56406. // Fill pixel data.
  56407. mipLevels = intArrayView[29]; // Number of mip levels.
  56408. var startIndex = 30;
  56409. var data = [];
  56410. var faceSize = Math.pow(_this._size, 2) * 3;
  56411. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56412. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56413. startIndex += faceSize;
  56414. }
  56415. var results = [];
  56416. var byteArray = null;
  56417. // Push each faces.
  56418. for (var k = 0; k < 6; k++) {
  56419. var dataFace = null;
  56420. // To be deprecated.
  56421. if (version === 1) {
  56422. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  56423. dataFace = data[j];
  56424. }
  56425. // If special cases.
  56426. if (!mipmapGenerator) {
  56427. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56428. // 3 channels of 1 bytes per pixel in bytes.
  56429. var byteBuffer = new ArrayBuffer(faceSize);
  56430. byteArray = new Uint8Array(byteBuffer);
  56431. }
  56432. for (var i = 0; i < _this._size * _this._size; i++) {
  56433. // Put in gamma space if requested.
  56434. if (_this._useInGammaSpace) {
  56435. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56436. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56437. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56438. }
  56439. // Convert to int texture for fallback.
  56440. if (byteArray) {
  56441. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56442. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56443. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56444. // May use luminance instead if the result is not accurate.
  56445. var max = Math.max(Math.max(r, g), b);
  56446. if (max > 255) {
  56447. var scale = 255 / max;
  56448. r *= scale;
  56449. g *= scale;
  56450. b *= scale;
  56451. }
  56452. byteArray[(i * 3) + 0] = r;
  56453. byteArray[(i * 3) + 1] = g;
  56454. byteArray[(i * 3) + 2] = b;
  56455. }
  56456. }
  56457. }
  56458. // Fill the array accordingly.
  56459. if (byteArray) {
  56460. results.push(byteArray);
  56461. }
  56462. else {
  56463. results.push(dataFace);
  56464. }
  56465. }
  56466. return results;
  56467. };
  56468. 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);
  56469. };
  56470. /**
  56471. * Occurs when the file is raw .hdr file.
  56472. */
  56473. HDRCubeTexture.prototype.loadHDRTexture = function () {
  56474. var _this = this;
  56475. var callback = function (buffer) {
  56476. // Extract the raw linear data.
  56477. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  56478. // Generate harmonics if needed.
  56479. if (_this._generateHarmonics) {
  56480. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  56481. _this.sphericalPolynomial = sphericalPolynomial;
  56482. }
  56483. var results = [];
  56484. var byteArray = null;
  56485. // Push each faces.
  56486. for (var j = 0; j < 6; j++) {
  56487. // Create uintarray fallback.
  56488. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56489. // 3 channels of 1 bytes per pixel in bytes.
  56490. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  56491. byteArray = new Uint8Array(byteBuffer);
  56492. }
  56493. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  56494. // If special cases.
  56495. if (_this._useInGammaSpace || byteArray) {
  56496. for (var i = 0; i < _this._size * _this._size; i++) {
  56497. // Put in gamma space if requested.
  56498. if (_this._useInGammaSpace) {
  56499. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56500. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56501. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56502. }
  56503. // Convert to int texture for fallback.
  56504. if (byteArray) {
  56505. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56506. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56507. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56508. // May use luminance instead if the result is not accurate.
  56509. var max = Math.max(Math.max(r, g), b);
  56510. if (max > 255) {
  56511. var scale = 255 / max;
  56512. r *= scale;
  56513. g *= scale;
  56514. b *= scale;
  56515. }
  56516. byteArray[(i * 3) + 0] = r;
  56517. byteArray[(i * 3) + 1] = g;
  56518. byteArray[(i * 3) + 2] = b;
  56519. }
  56520. }
  56521. }
  56522. if (byteArray) {
  56523. results.push(byteArray);
  56524. }
  56525. else {
  56526. results.push(dataFace);
  56527. }
  56528. }
  56529. return results;
  56530. };
  56531. var mipmapGenerator = null;
  56532. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  56533. // if (!this._noMipmap &&
  56534. // this._usePMREMGenerator) {
  56535. // mipmapGenerator = (data: ArrayBufferView[]) => {
  56536. // // Custom setup of the generator matching with the PBR shader values.
  56537. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  56538. // this._size,
  56539. // this._size,
  56540. // 0,
  56541. // 3,
  56542. // this.getScene().getEngine().getCaps().textureFloat,
  56543. // 2048,
  56544. // 0.25,
  56545. // false,
  56546. // true);
  56547. // return generator.filterCubeMap();
  56548. // };
  56549. // }
  56550. 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);
  56551. };
  56552. /**
  56553. * Starts the loading process of the texture.
  56554. */
  56555. HDRCubeTexture.prototype.loadTexture = function () {
  56556. if (this._isBABYLONPreprocessed) {
  56557. this.loadBabylonTexture();
  56558. }
  56559. else {
  56560. this.loadHDRTexture();
  56561. }
  56562. };
  56563. HDRCubeTexture.prototype.clone = function () {
  56564. var size = this._isBABYLONPreprocessed ? null : this._size;
  56565. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56566. // Base texture
  56567. newTexture.level = this.level;
  56568. newTexture.wrapU = this.wrapU;
  56569. newTexture.wrapV = this.wrapV;
  56570. newTexture.coordinatesIndex = this.coordinatesIndex;
  56571. newTexture.coordinatesMode = this.coordinatesMode;
  56572. return newTexture;
  56573. };
  56574. // Methods
  56575. HDRCubeTexture.prototype.delayLoad = function () {
  56576. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56577. return;
  56578. }
  56579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56580. this._texture = this._getFromCache(this.url, this._noMipmap);
  56581. if (!this._texture) {
  56582. this.loadTexture();
  56583. }
  56584. };
  56585. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56586. return this._textureMatrix;
  56587. };
  56588. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  56589. this._textureMatrix = value;
  56590. };
  56591. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56592. var texture = null;
  56593. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56594. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56595. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  56596. texture.name = parsedTexture.name;
  56597. texture.hasAlpha = parsedTexture.hasAlpha;
  56598. texture.level = parsedTexture.level;
  56599. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56600. texture.isBlocking = parsedTexture.isBlocking;
  56601. }
  56602. return texture;
  56603. };
  56604. HDRCubeTexture.prototype.serialize = function () {
  56605. if (!this.name) {
  56606. return null;
  56607. }
  56608. var serializationObject = {};
  56609. serializationObject.name = this.name;
  56610. serializationObject.hasAlpha = this.hasAlpha;
  56611. serializationObject.isCube = true;
  56612. serializationObject.level = this.level;
  56613. serializationObject.size = this._size;
  56614. serializationObject.coordinatesMode = this.coordinatesMode;
  56615. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56616. serializationObject.generateHarmonics = this._generateHarmonics;
  56617. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56618. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56619. serializationObject.customType = "BABYLON.HDRCubeTexture";
  56620. serializationObject.noMipmap = this._noMipmap;
  56621. serializationObject.isBlocking = this._isBlocking;
  56622. return serializationObject;
  56623. };
  56624. /**
  56625. * Saves as a file the data contained in the texture in a binary format.
  56626. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56627. * as the spherical used in the lighting.
  56628. * @param url The HDR file url.
  56629. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56630. * @param onError Method called if any error happens during download.
  56631. * @return The packed binary data.
  56632. */
  56633. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56634. if (onError === void 0) { onError = null; }
  56635. var callback = function (buffer) {
  56636. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56637. // Returns a URL you can use as a href.
  56638. var objUrl = window.URL.createObjectURL(data);
  56639. // Simulates a link to it and click to dowload.
  56640. var a = document.createElement("a");
  56641. document.body.appendChild(a);
  56642. a.style.display = "none";
  56643. a.href = objUrl;
  56644. a.download = "envmap.babylon.hdr";
  56645. a.click();
  56646. };
  56647. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56648. };
  56649. /**
  56650. * Serializes the data contained in the texture in a binary format.
  56651. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56652. * as the spherical used in the lighting.
  56653. * @param url The HDR file url.
  56654. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56655. * @param onError Method called if any error happens during download.
  56656. * @return The packed binary data.
  56657. */
  56658. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56659. if (onError === void 0) { onError = null; }
  56660. // Needs the url tho create the texture.
  56661. if (!url) {
  56662. return null;
  56663. }
  56664. // Check Power of two size.
  56665. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56666. return null;
  56667. }
  56668. // Coming Back in 3.1.
  56669. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  56670. return null;
  56671. };
  56672. return HDRCubeTexture;
  56673. }(BABYLON.BaseTexture));
  56674. HDRCubeTexture._facesMapping = [
  56675. "right",
  56676. "left",
  56677. "up",
  56678. "down",
  56679. "front",
  56680. "back"
  56681. ];
  56682. BABYLON.HDRCubeTexture = HDRCubeTexture;
  56683. })(BABYLON || (BABYLON = {}));
  56684. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  56685. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  56686. // Huge respect for a such great lib.
  56687. // Earcut license:
  56688. // Copyright (c) 2016, Mapbox
  56689. //
  56690. // Permission to use, copy, modify, and/or distribute this software for any purpose
  56691. // with or without fee is hereby granted, provided that the above copyright notice
  56692. // and this permission notice appear in all copies.
  56693. //
  56694. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  56695. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  56696. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  56697. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  56698. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  56699. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  56700. // THIS SOFTWARE.
  56701. var Earcut;
  56702. (function (Earcut) {
  56703. /**
  56704. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  56705. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  56706. * @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).
  56707. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  56708. */
  56709. function earcut(data, holeIndices, dim) {
  56710. dim = dim || 2;
  56711. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  56712. if (!outerNode)
  56713. return triangles;
  56714. var minX, minY, maxX, maxY, x, y, size;
  56715. if (hasHoles)
  56716. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  56717. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  56718. if (data.length > 80 * dim) {
  56719. minX = maxX = data[0];
  56720. minY = maxY = data[1];
  56721. for (var i = dim; i < outerLen; i += dim) {
  56722. x = data[i];
  56723. y = data[i + 1];
  56724. if (x < minX)
  56725. minX = x;
  56726. if (y < minY)
  56727. minY = y;
  56728. if (x > maxX)
  56729. maxX = x;
  56730. if (y > maxY)
  56731. maxY = y;
  56732. }
  56733. // minX, minY and size are later used to transform coords into integers for z-order calculation
  56734. size = Math.max(maxX - minX, maxY - minY);
  56735. }
  56736. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  56737. return triangles;
  56738. }
  56739. Earcut.earcut = earcut;
  56740. // create a circular doubly linked list from polygon points in the specified winding order
  56741. function linkedList(data, start, end, dim, clockwise) {
  56742. var i, last;
  56743. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  56744. for (i = start; i < end; i += dim)
  56745. last = insertNode(i, data[i], data[i + 1], last);
  56746. }
  56747. else {
  56748. for (i = end - dim; i >= start; i -= dim)
  56749. last = insertNode(i, data[i], data[i + 1], last);
  56750. }
  56751. if (last && equals(last, last.next)) {
  56752. removeNode(last);
  56753. last = last.next;
  56754. }
  56755. return last;
  56756. }
  56757. // eliminate colinear or duplicate points
  56758. function filterPoints(start, end) {
  56759. if (!start)
  56760. return start;
  56761. if (!end)
  56762. end = start;
  56763. var p = start, again;
  56764. do {
  56765. again = false;
  56766. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  56767. removeNode(p);
  56768. p = end = p.prev;
  56769. if (p === p.next)
  56770. return null;
  56771. again = true;
  56772. }
  56773. else {
  56774. p = p.next;
  56775. }
  56776. } while (again || p !== end);
  56777. return end;
  56778. }
  56779. // main ear slicing loop which triangulates a polygon (given as a linked list)
  56780. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  56781. if (!ear)
  56782. return;
  56783. // interlink polygon nodes in z-order
  56784. if (!pass && size)
  56785. indexCurve(ear, minX, minY, size);
  56786. var stop = ear, prev, next;
  56787. // iterate through ears, slicing them one by one
  56788. while (ear.prev !== ear.next) {
  56789. prev = ear.prev;
  56790. next = ear.next;
  56791. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  56792. // cut off the triangle
  56793. triangles.push(prev.i / dim);
  56794. triangles.push(ear.i / dim);
  56795. triangles.push(next.i / dim);
  56796. removeNode(ear);
  56797. // skipping the next vertice leads to less sliver triangles
  56798. ear = next.next;
  56799. stop = next.next;
  56800. continue;
  56801. }
  56802. ear = next;
  56803. // if we looped through the whole remaining polygon and can't find any more ears
  56804. if (ear === stop) {
  56805. // try filtering points and slicing again
  56806. if (!pass) {
  56807. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  56808. // if this didn't work, try curing all small self-intersections locally
  56809. }
  56810. else if (pass === 1) {
  56811. ear = cureLocalIntersections(ear, triangles, dim);
  56812. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  56813. // as a last resort, try splitting the remaining polygon into two
  56814. }
  56815. else if (pass === 2) {
  56816. splitEarcut(ear, triangles, dim, minX, minY, size);
  56817. }
  56818. break;
  56819. }
  56820. }
  56821. }
  56822. // check whether a polygon node forms a valid ear with adjacent nodes
  56823. function isEar(ear) {
  56824. var a = ear.prev, b = ear, c = ear.next;
  56825. if (area(a, b, c) >= 0)
  56826. return false; // reflex, can't be an ear
  56827. // now make sure we don't have other points inside the potential ear
  56828. var p = ear.next.next;
  56829. while (p !== ear.prev) {
  56830. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56831. area(p.prev, p, p.next) >= 0)
  56832. return false;
  56833. p = p.next;
  56834. }
  56835. return true;
  56836. }
  56837. function isEarHashed(ear, minX, minY, size) {
  56838. var a = ear.prev, b = ear, c = ear.next;
  56839. if (area(a, b, c) >= 0)
  56840. return false; // reflex, can't be an ear
  56841. // triangle bbox; min & max are calculated like this for speed
  56842. 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);
  56843. // z-order range for the current triangle bbox;
  56844. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  56845. // first look for points inside the triangle in increasing z-order
  56846. var p = ear.nextZ;
  56847. while (p && p.z <= maxZ) {
  56848. if (p !== ear.prev &&
  56849. p !== ear.next &&
  56850. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56851. area(p.prev, p, p.next) >= 0)
  56852. return false;
  56853. p = p.nextZ;
  56854. }
  56855. // then look for points in decreasing z-order
  56856. p = ear.prevZ;
  56857. while (p && p.z >= minZ) {
  56858. if (p !== ear.prev &&
  56859. p !== ear.next &&
  56860. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56861. area(p.prev, p, p.next) >= 0)
  56862. return false;
  56863. p = p.prevZ;
  56864. }
  56865. return true;
  56866. }
  56867. // go through all polygon nodes and cure small local self-intersections
  56868. function cureLocalIntersections(start, triangles, dim) {
  56869. var p = start;
  56870. do {
  56871. var a = p.prev, b = p.next.next;
  56872. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  56873. triangles.push(a.i / dim);
  56874. triangles.push(p.i / dim);
  56875. triangles.push(b.i / dim);
  56876. // remove two nodes involved
  56877. removeNode(p);
  56878. removeNode(p.next);
  56879. p = start = b;
  56880. }
  56881. p = p.next;
  56882. } while (p !== start);
  56883. return p;
  56884. }
  56885. // try splitting polygon into two and triangulate them independently
  56886. function splitEarcut(start, triangles, dim, minX, minY, size) {
  56887. // look for a valid diagonal that divides the polygon into two
  56888. var a = start;
  56889. do {
  56890. var b = a.next.next;
  56891. while (b !== a.prev) {
  56892. if (a.i !== b.i && isValidDiagonal(a, b)) {
  56893. // split the polygon in two by the diagonal
  56894. var c = splitPolygon(a, b);
  56895. // filter colinear points around the cuts
  56896. a = filterPoints(a, a.next);
  56897. c = filterPoints(c, c.next);
  56898. // run earcut on each half
  56899. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  56900. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  56901. return;
  56902. }
  56903. b = b.next;
  56904. }
  56905. a = a.next;
  56906. } while (a !== start);
  56907. }
  56908. // link every hole into the outer loop, producing a single-ring polygon without holes
  56909. function eliminateHoles(data, holeIndices, outerNode, dim) {
  56910. var queue = [], i, len, start, end, list;
  56911. for (i = 0, len = holeIndices.length; i < len; i++) {
  56912. start = holeIndices[i] * dim;
  56913. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  56914. list = linkedList(data, start, end, dim, false);
  56915. if (list === list.next)
  56916. list.steiner = true;
  56917. queue.push(getLeftmost(list));
  56918. }
  56919. queue.sort(compareX);
  56920. // process holes from left to right
  56921. for (i = 0; i < queue.length; i++) {
  56922. eliminateHole(queue[i], outerNode);
  56923. outerNode = filterPoints(outerNode, outerNode.next);
  56924. }
  56925. return outerNode;
  56926. }
  56927. function compareX(a, b) {
  56928. return a.x - b.x;
  56929. }
  56930. // find a bridge between vertices that connects hole with an outer ring and and link it
  56931. function eliminateHole(hole, outerNode) {
  56932. outerNode = findHoleBridge(hole, outerNode);
  56933. if (outerNode) {
  56934. var b = splitPolygon(outerNode, hole);
  56935. filterPoints(b, b.next);
  56936. }
  56937. }
  56938. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  56939. function findHoleBridge(hole, outerNode) {
  56940. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  56941. // find a segment intersected by a ray from the hole's leftmost point to the left;
  56942. // segment's endpoint with lesser x will be potential connection point
  56943. do {
  56944. if (hy <= p.y && hy >= p.next.y) {
  56945. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  56946. if (x <= hx && x > qx) {
  56947. qx = x;
  56948. if (x === hx) {
  56949. if (hy === p.y)
  56950. return p;
  56951. if (hy === p.next.y)
  56952. return p.next;
  56953. }
  56954. m = p.x < p.next.x ? p : p.next;
  56955. }
  56956. }
  56957. p = p.next;
  56958. } while (p !== outerNode);
  56959. if (!m)
  56960. return null;
  56961. if (hx === qx)
  56962. return m.prev; // hole touches outer segment; pick lower endpoint
  56963. // look for points inside the triangle of hole point, segment intersection and endpoint;
  56964. // if there are no points found, we have a valid connection;
  56965. // otherwise choose the point of the minimum angle with the ray as connection point
  56966. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  56967. p = m.next;
  56968. while (p !== stop) {
  56969. if (hx >= p.x &&
  56970. p.x >= mx &&
  56971. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  56972. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  56973. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  56974. m = p;
  56975. tanMin = tan;
  56976. }
  56977. }
  56978. p = p.next;
  56979. }
  56980. return m;
  56981. }
  56982. // interlink polygon nodes in z-order
  56983. function indexCurve(start, minX, minY, size) {
  56984. var p = start;
  56985. do {
  56986. if (p.z === null)
  56987. p.z = zOrder(p.x, p.y, minX, minY, size);
  56988. p.prevZ = p.prev;
  56989. p.nextZ = p.next;
  56990. p = p.next;
  56991. } while (p !== start);
  56992. p.prevZ.nextZ = null;
  56993. p.prevZ = null;
  56994. sortLinked(p);
  56995. }
  56996. // Simon Tatham's linked list merge sort algorithm
  56997. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  56998. function sortLinked(list) {
  56999. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  57000. do {
  57001. p = list;
  57002. list = null;
  57003. tail = null;
  57004. numMerges = 0;
  57005. while (p) {
  57006. numMerges++;
  57007. q = p;
  57008. pSize = 0;
  57009. for (i = 0; i < inSize; i++) {
  57010. pSize++;
  57011. q = q.nextZ;
  57012. if (!q)
  57013. break;
  57014. }
  57015. qSize = inSize;
  57016. while (pSize > 0 || (qSize > 0 && q)) {
  57017. if (pSize === 0) {
  57018. e = q;
  57019. q = q.nextZ;
  57020. qSize--;
  57021. }
  57022. else if (qSize === 0 || !q) {
  57023. e = p;
  57024. p = p.nextZ;
  57025. pSize--;
  57026. }
  57027. else if (p.z <= q.z) {
  57028. e = p;
  57029. p = p.nextZ;
  57030. pSize--;
  57031. }
  57032. else {
  57033. e = q;
  57034. q = q.nextZ;
  57035. qSize--;
  57036. }
  57037. if (tail)
  57038. tail.nextZ = e;
  57039. else
  57040. list = e;
  57041. e.prevZ = tail;
  57042. tail = e;
  57043. }
  57044. p = q;
  57045. }
  57046. tail.nextZ = null;
  57047. inSize *= 2;
  57048. } while (numMerges > 1);
  57049. return list;
  57050. }
  57051. // z-order of a point given coords and size of the data bounding box
  57052. function zOrder(x, y, minX, minY, size) {
  57053. // coords are transformed into non-negative 15-bit integer range
  57054. x = 32767 * (x - minX) / size;
  57055. y = 32767 * (y - minY) / size;
  57056. x = (x | (x << 8)) & 0x00FF00FF;
  57057. x = (x | (x << 4)) & 0x0F0F0F0F;
  57058. x = (x | (x << 2)) & 0x33333333;
  57059. x = (x | (x << 1)) & 0x55555555;
  57060. y = (y | (y << 8)) & 0x00FF00FF;
  57061. y = (y | (y << 4)) & 0x0F0F0F0F;
  57062. y = (y | (y << 2)) & 0x33333333;
  57063. y = (y | (y << 1)) & 0x55555555;
  57064. return x | (y << 1);
  57065. }
  57066. // find the leftmost node of a polygon ring
  57067. function getLeftmost(start) {
  57068. var p = start, leftmost = start;
  57069. do {
  57070. if (p.x < leftmost.x)
  57071. leftmost = p;
  57072. p = p.next;
  57073. } while (p !== start);
  57074. return leftmost;
  57075. }
  57076. // check if a point lies within a convex triangle
  57077. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  57078. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  57079. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  57080. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  57081. }
  57082. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  57083. function isValidDiagonal(a, b) {
  57084. return a.next.i !== b.i &&
  57085. a.prev.i !== b.i &&
  57086. !intersectsPolygon(a, b) &&
  57087. locallyInside(a, b) &&
  57088. locallyInside(b, a) &&
  57089. middleInside(a, b);
  57090. }
  57091. // signed area of a triangle
  57092. function area(p, q, r) {
  57093. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  57094. }
  57095. // check if two points are equal
  57096. function equals(p1, p2) {
  57097. return p1.x === p2.x && p1.y === p2.y;
  57098. }
  57099. // check if two segments intersect
  57100. function intersects(p1, q1, p2, q2) {
  57101. if ((equals(p1, q1) && equals(p2, q2)) ||
  57102. (equals(p1, q2) && equals(p2, q1)))
  57103. return true;
  57104. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  57105. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  57106. }
  57107. // check if a polygon diagonal intersects any polygon segments
  57108. function intersectsPolygon(a, b) {
  57109. var p = a;
  57110. do {
  57111. if (p.i !== a.i &&
  57112. p.next.i !== a.i &&
  57113. p.i !== b.i &&
  57114. p.next.i !== b.i &&
  57115. intersects(p, p.next, a, b))
  57116. return true;
  57117. p = p.next;
  57118. } while (p !== a);
  57119. return false;
  57120. }
  57121. // check if a polygon diagonal is locally inside the polygon
  57122. function locallyInside(a, b) {
  57123. return area(a.prev, a, a.next) < 0
  57124. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  57125. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  57126. }
  57127. // check if the middle point of a polygon diagonal is inside the polygon
  57128. function middleInside(a, b) {
  57129. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  57130. do {
  57131. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  57132. inside = !inside;
  57133. p = p.next;
  57134. } while (p !== a);
  57135. return inside;
  57136. }
  57137. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  57138. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  57139. function splitPolygon(a, b) {
  57140. 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;
  57141. a.next = b;
  57142. b.prev = a;
  57143. a2.next = an;
  57144. an.prev = a2;
  57145. b2.next = a2;
  57146. a2.prev = b2;
  57147. bp.next = b2;
  57148. b2.prev = bp;
  57149. return b2;
  57150. }
  57151. // create a node and optionally link it with previous one (in a circular doubly linked list)
  57152. function insertNode(i, x, y, last) {
  57153. var p = new Node(i, x, y);
  57154. if (!last) {
  57155. p.prev = p;
  57156. p.next = p;
  57157. }
  57158. else {
  57159. p.next = last.next;
  57160. p.prev = last;
  57161. last.next.prev = p;
  57162. last.next = p;
  57163. }
  57164. return p;
  57165. }
  57166. function removeNode(p) {
  57167. p.next.prev = p.prev;
  57168. p.prev.next = p.next;
  57169. if (p.prevZ)
  57170. p.prevZ.nextZ = p.nextZ;
  57171. if (p.nextZ)
  57172. p.nextZ.prevZ = p.prevZ;
  57173. }
  57174. function Node(i, x, y) {
  57175. // vertice index in coordinates array
  57176. this.i = i;
  57177. // vertex coordinates
  57178. this.x = x;
  57179. this.y = y;
  57180. // previous and next vertice nodes in a polygon ring
  57181. this.prev = null;
  57182. this.next = null;
  57183. // z-order curve value
  57184. this.z = null;
  57185. // previous and next nodes in z-order
  57186. this.prevZ = null;
  57187. this.nextZ = null;
  57188. // indicates whether this is a steiner point
  57189. this.steiner = false;
  57190. }
  57191. /**
  57192. * return a percentage difference between the polygon area and its triangulation area;
  57193. * used to verify correctness of triangulation
  57194. */
  57195. function deviation(data, holeIndices, dim, triangles) {
  57196. var hasHoles = holeIndices && holeIndices.length;
  57197. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  57198. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  57199. if (hasHoles) {
  57200. for (var i = 0, len = holeIndices.length; i < len; i++) {
  57201. var start = holeIndices[i] * dim;
  57202. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57203. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  57204. }
  57205. }
  57206. var trianglesArea = 0;
  57207. for (i = 0; i < triangles.length; i += 3) {
  57208. var a = triangles[i] * dim;
  57209. var b = triangles[i + 1] * dim;
  57210. var c = triangles[i + 2] * dim;
  57211. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  57212. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  57213. }
  57214. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  57215. }
  57216. Earcut.deviation = deviation;
  57217. ;
  57218. function signedArea(data, start, end, dim) {
  57219. var sum = 0;
  57220. for (var i = start, j = end - dim; i < end; i += dim) {
  57221. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  57222. j = i;
  57223. }
  57224. return sum;
  57225. }
  57226. /**
  57227. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  57228. */
  57229. function flatten(data) {
  57230. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  57231. for (var i = 0; i < data.length; i++) {
  57232. for (var j = 0; j < data[i].length; j++) {
  57233. for (var d = 0; d < dim; d++)
  57234. result.vertices.push(data[i][j][d]);
  57235. }
  57236. if (i > 0) {
  57237. holeIndex += data[i - 1].length;
  57238. result.holes.push(holeIndex);
  57239. }
  57240. }
  57241. return result;
  57242. }
  57243. Earcut.flatten = flatten;
  57244. ;
  57245. })(Earcut || (Earcut = {}));
  57246. //# sourceMappingURL=babylon.earcut.js.map
  57247. /// <reference path="..\Math\babylon.math.ts" />
  57248. var BABYLON;
  57249. (function (BABYLON) {
  57250. var IndexedVector2 = (function (_super) {
  57251. __extends(IndexedVector2, _super);
  57252. function IndexedVector2(original, index) {
  57253. var _this = _super.call(this, original.x, original.y) || this;
  57254. _this.index = index;
  57255. return _this;
  57256. }
  57257. return IndexedVector2;
  57258. }(BABYLON.Vector2));
  57259. var PolygonPoints = (function () {
  57260. function PolygonPoints() {
  57261. this.elements = new Array();
  57262. }
  57263. PolygonPoints.prototype.add = function (originalPoints) {
  57264. var _this = this;
  57265. var result = new Array();
  57266. originalPoints.forEach(function (point) {
  57267. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  57268. var newPoint = new IndexedVector2(point, _this.elements.length);
  57269. result.push(newPoint);
  57270. _this.elements.push(newPoint);
  57271. }
  57272. });
  57273. return result;
  57274. };
  57275. PolygonPoints.prototype.computeBounds = function () {
  57276. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  57277. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  57278. this.elements.forEach(function (point) {
  57279. // x
  57280. if (point.x < lmin.x) {
  57281. lmin.x = point.x;
  57282. }
  57283. else if (point.x > lmax.x) {
  57284. lmax.x = point.x;
  57285. }
  57286. // y
  57287. if (point.y < lmin.y) {
  57288. lmin.y = point.y;
  57289. }
  57290. else if (point.y > lmax.y) {
  57291. lmax.y = point.y;
  57292. }
  57293. });
  57294. return {
  57295. min: lmin,
  57296. max: lmax,
  57297. width: lmax.x - lmin.x,
  57298. height: lmax.y - lmin.y
  57299. };
  57300. };
  57301. return PolygonPoints;
  57302. }());
  57303. var Polygon = (function () {
  57304. function Polygon() {
  57305. }
  57306. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  57307. return [
  57308. new BABYLON.Vector2(xmin, ymin),
  57309. new BABYLON.Vector2(xmax, ymin),
  57310. new BABYLON.Vector2(xmax, ymax),
  57311. new BABYLON.Vector2(xmin, ymax)
  57312. ];
  57313. };
  57314. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  57315. if (cx === void 0) { cx = 0; }
  57316. if (cy === void 0) { cy = 0; }
  57317. if (numberOfSides === void 0) { numberOfSides = 32; }
  57318. var result = new Array();
  57319. var angle = 0;
  57320. var increment = (Math.PI * 2) / numberOfSides;
  57321. for (var i = 0; i < numberOfSides; i++) {
  57322. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  57323. angle -= increment;
  57324. }
  57325. return result;
  57326. };
  57327. Polygon.Parse = function (input) {
  57328. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  57329. var i, result = [];
  57330. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  57331. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  57332. }
  57333. return result;
  57334. };
  57335. Polygon.StartingAt = function (x, y) {
  57336. return BABYLON.Path2.StartingAt(x, y);
  57337. };
  57338. return Polygon;
  57339. }());
  57340. BABYLON.Polygon = Polygon;
  57341. var PolygonMeshBuilder = (function () {
  57342. function PolygonMeshBuilder(name, contours, scene) {
  57343. this._points = new PolygonPoints();
  57344. this._outlinepoints = new PolygonPoints();
  57345. this._holes = [];
  57346. this._epoints = new Array();
  57347. this._eholes = new Array();
  57348. this._name = name;
  57349. this._scene = scene;
  57350. var points;
  57351. if (contours instanceof BABYLON.Path2) {
  57352. points = contours.getPoints();
  57353. }
  57354. else {
  57355. points = contours;
  57356. }
  57357. this._addToepoint(points);
  57358. this._points.add(points);
  57359. this._outlinepoints.add(points);
  57360. }
  57361. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  57362. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  57363. var p = points_1[_i];
  57364. this._epoints.push(p.x, p.y);
  57365. }
  57366. };
  57367. PolygonMeshBuilder.prototype.addHole = function (hole) {
  57368. this._points.add(hole);
  57369. var holepoints = new PolygonPoints();
  57370. holepoints.add(hole);
  57371. this._holes.push(holepoints);
  57372. this._eholes.push(this._epoints.length / 2);
  57373. this._addToepoint(hole);
  57374. return this;
  57375. };
  57376. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  57377. var _this = this;
  57378. if (updatable === void 0) { updatable = false; }
  57379. var result = new BABYLON.Mesh(this._name, this._scene);
  57380. var normals = [];
  57381. var positions = [];
  57382. var uvs = [];
  57383. var bounds = this._points.computeBounds();
  57384. this._points.elements.forEach(function (p) {
  57385. normals.push(0, 1.0, 0);
  57386. positions.push(p.x, 0, p.y);
  57387. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  57388. });
  57389. var indices = [];
  57390. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  57391. for (var i = 0; i < res.length; i++) {
  57392. indices.push(res[i]);
  57393. }
  57394. if (depth > 0) {
  57395. var positionscount = (positions.length / 3); //get the current pointcount
  57396. this._points.elements.forEach(function (p) {
  57397. normals.push(0, -1.0, 0);
  57398. positions.push(p.x, -depth, p.y);
  57399. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  57400. });
  57401. var totalCount = indices.length;
  57402. for (var i = 0; i < totalCount; i += 3) {
  57403. var i0 = indices[i + 0];
  57404. var i1 = indices[i + 1];
  57405. var i2 = indices[i + 2];
  57406. indices.push(i2 + positionscount);
  57407. indices.push(i1 + positionscount);
  57408. indices.push(i0 + positionscount);
  57409. }
  57410. //Add the sides
  57411. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  57412. this._holes.forEach(function (hole) {
  57413. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  57414. });
  57415. }
  57416. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  57417. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  57418. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  57419. result.setIndices(indices);
  57420. return result;
  57421. };
  57422. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  57423. var StartIndex = positions.length / 3;
  57424. var ulength = 0;
  57425. for (var i = 0; i < points.elements.length; i++) {
  57426. var p = points.elements[i];
  57427. var p1;
  57428. if ((i + 1) > points.elements.length - 1) {
  57429. p1 = points.elements[0];
  57430. }
  57431. else {
  57432. p1 = points.elements[i + 1];
  57433. }
  57434. positions.push(p.x, 0, p.y);
  57435. positions.push(p.x, -depth, p.y);
  57436. positions.push(p1.x, 0, p1.y);
  57437. positions.push(p1.x, -depth, p1.y);
  57438. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  57439. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  57440. var v3 = v2.subtract(v1);
  57441. var v4 = new BABYLON.Vector3(0, 1, 0);
  57442. var vn = BABYLON.Vector3.Cross(v3, v4);
  57443. vn = vn.normalize();
  57444. uvs.push(ulength / bounds.width, 0);
  57445. uvs.push(ulength / bounds.width, 1);
  57446. ulength += v3.length();
  57447. uvs.push((ulength / bounds.width), 0);
  57448. uvs.push((ulength / bounds.width), 1);
  57449. if (!flip) {
  57450. normals.push(-vn.x, -vn.y, -vn.z);
  57451. normals.push(-vn.x, -vn.y, -vn.z);
  57452. normals.push(-vn.x, -vn.y, -vn.z);
  57453. normals.push(-vn.x, -vn.y, -vn.z);
  57454. indices.push(StartIndex);
  57455. indices.push(StartIndex + 1);
  57456. indices.push(StartIndex + 2);
  57457. indices.push(StartIndex + 1);
  57458. indices.push(StartIndex + 3);
  57459. indices.push(StartIndex + 2);
  57460. }
  57461. else {
  57462. normals.push(vn.x, vn.y, vn.z);
  57463. normals.push(vn.x, vn.y, vn.z);
  57464. normals.push(vn.x, vn.y, vn.z);
  57465. normals.push(vn.x, vn.y, vn.z);
  57466. indices.push(StartIndex);
  57467. indices.push(StartIndex + 2);
  57468. indices.push(StartIndex + 1);
  57469. indices.push(StartIndex + 1);
  57470. indices.push(StartIndex + 2);
  57471. indices.push(StartIndex + 3);
  57472. }
  57473. StartIndex += 4;
  57474. }
  57475. ;
  57476. };
  57477. return PolygonMeshBuilder;
  57478. }());
  57479. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  57480. })(BABYLON || (BABYLON = {}));
  57481. //# sourceMappingURL=babylon.polygonMesh.js.map
  57482. var BABYLON;
  57483. (function (BABYLON) {
  57484. // Unique ID when we import meshes from Babylon to CSG
  57485. var currentCSGMeshId = 0;
  57486. // # class Vertex
  57487. // Represents a vertex of a polygon. Use your own vertex class instead of this
  57488. // one to provide additional features like texture coordinates and vertex
  57489. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  57490. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  57491. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  57492. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  57493. // is not used anywhere else.
  57494. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  57495. var Vertex = (function () {
  57496. function Vertex(pos, normal, uv) {
  57497. this.pos = pos;
  57498. this.normal = normal;
  57499. this.uv = uv;
  57500. }
  57501. Vertex.prototype.clone = function () {
  57502. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  57503. };
  57504. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  57505. // orientation of a polygon is flipped.
  57506. Vertex.prototype.flip = function () {
  57507. this.normal = this.normal.scale(-1);
  57508. };
  57509. // Create a new vertex between this vertex and `other` by linearly
  57510. // interpolating all properties using a parameter of `t`. Subclasses should
  57511. // override this to interpolate additional properties.
  57512. Vertex.prototype.interpolate = function (other, t) {
  57513. 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));
  57514. };
  57515. return Vertex;
  57516. }());
  57517. // # class Plane
  57518. // Represents a plane in 3D space.
  57519. var Plane = (function () {
  57520. function Plane(normal, w) {
  57521. this.normal = normal;
  57522. this.w = w;
  57523. }
  57524. Plane.FromPoints = function (a, b, c) {
  57525. var v0 = c.subtract(a);
  57526. var v1 = b.subtract(a);
  57527. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  57528. return null;
  57529. }
  57530. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  57531. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  57532. };
  57533. Plane.prototype.clone = function () {
  57534. return new Plane(this.normal.clone(), this.w);
  57535. };
  57536. Plane.prototype.flip = function () {
  57537. this.normal.scaleInPlace(-1);
  57538. this.w = -this.w;
  57539. };
  57540. // Split `polygon` by this plane if needed, then put the polygon or polygon
  57541. // fragments in the appropriate lists. Coplanar polygons go into either
  57542. // `coplanarFront` or `coplanarBack` depending on their orientation with
  57543. // respect to this plane. Polygons in front or in back of this plane go into
  57544. // either `front` or `back`.
  57545. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  57546. var COPLANAR = 0;
  57547. var FRONT = 1;
  57548. var BACK = 2;
  57549. var SPANNING = 3;
  57550. // Classify each point as well as the entire polygon into one of the above
  57551. // four classes.
  57552. var polygonType = 0;
  57553. var types = [];
  57554. var i;
  57555. var t;
  57556. for (i = 0; i < polygon.vertices.length; i++) {
  57557. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  57558. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  57559. polygonType |= type;
  57560. types.push(type);
  57561. }
  57562. // Put the polygon in the correct list, splitting it when necessary.
  57563. switch (polygonType) {
  57564. case COPLANAR:
  57565. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  57566. break;
  57567. case FRONT:
  57568. front.push(polygon);
  57569. break;
  57570. case BACK:
  57571. back.push(polygon);
  57572. break;
  57573. case SPANNING:
  57574. var f = [], b = [];
  57575. for (i = 0; i < polygon.vertices.length; i++) {
  57576. var j = (i + 1) % polygon.vertices.length;
  57577. var ti = types[i], tj = types[j];
  57578. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  57579. if (ti !== BACK)
  57580. f.push(vi);
  57581. if (ti !== FRONT)
  57582. b.push(ti !== BACK ? vi.clone() : vi);
  57583. if ((ti | tj) === SPANNING) {
  57584. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  57585. var v = vi.interpolate(vj, t);
  57586. f.push(v);
  57587. b.push(v.clone());
  57588. }
  57589. }
  57590. var poly;
  57591. if (f.length >= 3) {
  57592. poly = new Polygon(f, polygon.shared);
  57593. if (poly.plane)
  57594. front.push(poly);
  57595. }
  57596. if (b.length >= 3) {
  57597. poly = new Polygon(b, polygon.shared);
  57598. if (poly.plane)
  57599. back.push(poly);
  57600. }
  57601. break;
  57602. }
  57603. };
  57604. return Plane;
  57605. }());
  57606. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  57607. // point is on the plane.
  57608. Plane.EPSILON = 1e-5;
  57609. // # class Polygon
  57610. // Represents a convex polygon. The vertices used to initialize a polygon must
  57611. // be coplanar and form a convex loop.
  57612. //
  57613. // Each convex polygon has a `shared` property, which is shared between all
  57614. // polygons that are clones of each other or were split from the same polygon.
  57615. // This can be used to define per-polygon properties (such as surface color).
  57616. var Polygon = (function () {
  57617. function Polygon(vertices, shared) {
  57618. this.vertices = vertices;
  57619. this.shared = shared;
  57620. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  57621. }
  57622. Polygon.prototype.clone = function () {
  57623. var vertices = this.vertices.map(function (v) { return v.clone(); });
  57624. return new Polygon(vertices, this.shared);
  57625. };
  57626. Polygon.prototype.flip = function () {
  57627. this.vertices.reverse().map(function (v) { v.flip(); });
  57628. this.plane.flip();
  57629. };
  57630. return Polygon;
  57631. }());
  57632. // # class Node
  57633. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  57634. // by picking a polygon to split along. That polygon (and all other coplanar
  57635. // polygons) are added directly to that node and the other polygons are added to
  57636. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  57637. // no distinction between internal and leaf nodes.
  57638. var Node = (function () {
  57639. function Node(polygons) {
  57640. this.plane = null;
  57641. this.front = null;
  57642. this.back = null;
  57643. this.polygons = [];
  57644. if (polygons) {
  57645. this.build(polygons);
  57646. }
  57647. }
  57648. Node.prototype.clone = function () {
  57649. var node = new Node();
  57650. node.plane = this.plane && this.plane.clone();
  57651. node.front = this.front && this.front.clone();
  57652. node.back = this.back && this.back.clone();
  57653. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  57654. return node;
  57655. };
  57656. // Convert solid space to empty space and empty space to solid space.
  57657. Node.prototype.invert = function () {
  57658. for (var i = 0; i < this.polygons.length; i++) {
  57659. this.polygons[i].flip();
  57660. }
  57661. if (this.plane) {
  57662. this.plane.flip();
  57663. }
  57664. if (this.front) {
  57665. this.front.invert();
  57666. }
  57667. if (this.back) {
  57668. this.back.invert();
  57669. }
  57670. var temp = this.front;
  57671. this.front = this.back;
  57672. this.back = temp;
  57673. };
  57674. // Recursively remove all polygons in `polygons` that are inside this BSP
  57675. // tree.
  57676. Node.prototype.clipPolygons = function (polygons) {
  57677. if (!this.plane)
  57678. return polygons.slice();
  57679. var front = [], back = [];
  57680. for (var i = 0; i < polygons.length; i++) {
  57681. this.plane.splitPolygon(polygons[i], front, back, front, back);
  57682. }
  57683. if (this.front) {
  57684. front = this.front.clipPolygons(front);
  57685. }
  57686. if (this.back) {
  57687. back = this.back.clipPolygons(back);
  57688. }
  57689. else {
  57690. back = [];
  57691. }
  57692. return front.concat(back);
  57693. };
  57694. // Remove all polygons in this BSP tree that are inside the other BSP tree
  57695. // `bsp`.
  57696. Node.prototype.clipTo = function (bsp) {
  57697. this.polygons = bsp.clipPolygons(this.polygons);
  57698. if (this.front)
  57699. this.front.clipTo(bsp);
  57700. if (this.back)
  57701. this.back.clipTo(bsp);
  57702. };
  57703. // Return a list of all polygons in this BSP tree.
  57704. Node.prototype.allPolygons = function () {
  57705. var polygons = this.polygons.slice();
  57706. if (this.front)
  57707. polygons = polygons.concat(this.front.allPolygons());
  57708. if (this.back)
  57709. polygons = polygons.concat(this.back.allPolygons());
  57710. return polygons;
  57711. };
  57712. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  57713. // new polygons are filtered down to the bottom of the tree and become new
  57714. // nodes there. Each set of polygons is partitioned using the first polygon
  57715. // (no heuristic is used to pick a good split).
  57716. Node.prototype.build = function (polygons) {
  57717. if (!polygons.length)
  57718. return;
  57719. if (!this.plane)
  57720. this.plane = polygons[0].plane.clone();
  57721. var front = [], back = [];
  57722. for (var i = 0; i < polygons.length; i++) {
  57723. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  57724. }
  57725. if (front.length) {
  57726. if (!this.front)
  57727. this.front = new Node();
  57728. this.front.build(front);
  57729. }
  57730. if (back.length) {
  57731. if (!this.back)
  57732. this.back = new Node();
  57733. this.back.build(back);
  57734. }
  57735. };
  57736. return Node;
  57737. }());
  57738. var CSG = (function () {
  57739. function CSG() {
  57740. this.polygons = new Array();
  57741. }
  57742. // Convert BABYLON.Mesh to BABYLON.CSG
  57743. CSG.FromMesh = function (mesh) {
  57744. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  57745. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  57746. if (mesh instanceof BABYLON.Mesh) {
  57747. mesh.computeWorldMatrix(true);
  57748. matrix = mesh.getWorldMatrix();
  57749. meshPosition = mesh.position.clone();
  57750. meshRotation = mesh.rotation.clone();
  57751. if (mesh.rotationQuaternion) {
  57752. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  57753. }
  57754. meshScaling = mesh.scaling.clone();
  57755. }
  57756. else {
  57757. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  57758. }
  57759. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57760. var subMeshes = mesh.subMeshes;
  57761. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  57762. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  57763. vertices = [];
  57764. for (var j = 0; j < 3; j++) {
  57765. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  57766. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  57767. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  57768. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  57769. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  57770. vertex = new Vertex(position, normal, uv);
  57771. vertices.push(vertex);
  57772. }
  57773. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  57774. // To handle the case of degenerated triangle
  57775. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  57776. if (polygon.plane)
  57777. polygons.push(polygon);
  57778. }
  57779. }
  57780. var csg = CSG.FromPolygons(polygons);
  57781. csg.matrix = matrix;
  57782. csg.position = meshPosition;
  57783. csg.rotation = meshRotation;
  57784. csg.scaling = meshScaling;
  57785. csg.rotationQuaternion = meshRotationQuaternion;
  57786. currentCSGMeshId++;
  57787. return csg;
  57788. };
  57789. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  57790. CSG.FromPolygons = function (polygons) {
  57791. var csg = new CSG();
  57792. csg.polygons = polygons;
  57793. return csg;
  57794. };
  57795. CSG.prototype.clone = function () {
  57796. var csg = new CSG();
  57797. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  57798. csg.copyTransformAttributes(this);
  57799. return csg;
  57800. };
  57801. CSG.prototype.toPolygons = function () {
  57802. return this.polygons;
  57803. };
  57804. CSG.prototype.union = function (csg) {
  57805. var a = new Node(this.clone().polygons);
  57806. var b = new Node(csg.clone().polygons);
  57807. a.clipTo(b);
  57808. b.clipTo(a);
  57809. b.invert();
  57810. b.clipTo(a);
  57811. b.invert();
  57812. a.build(b.allPolygons());
  57813. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57814. };
  57815. CSG.prototype.unionInPlace = function (csg) {
  57816. var a = new Node(this.polygons);
  57817. var b = new Node(csg.polygons);
  57818. a.clipTo(b);
  57819. b.clipTo(a);
  57820. b.invert();
  57821. b.clipTo(a);
  57822. b.invert();
  57823. a.build(b.allPolygons());
  57824. this.polygons = a.allPolygons();
  57825. };
  57826. CSG.prototype.subtract = function (csg) {
  57827. var a = new Node(this.clone().polygons);
  57828. var b = new Node(csg.clone().polygons);
  57829. a.invert();
  57830. a.clipTo(b);
  57831. b.clipTo(a);
  57832. b.invert();
  57833. b.clipTo(a);
  57834. b.invert();
  57835. a.build(b.allPolygons());
  57836. a.invert();
  57837. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57838. };
  57839. CSG.prototype.subtractInPlace = function (csg) {
  57840. var a = new Node(this.polygons);
  57841. var b = new Node(csg.polygons);
  57842. a.invert();
  57843. a.clipTo(b);
  57844. b.clipTo(a);
  57845. b.invert();
  57846. b.clipTo(a);
  57847. b.invert();
  57848. a.build(b.allPolygons());
  57849. a.invert();
  57850. this.polygons = a.allPolygons();
  57851. };
  57852. CSG.prototype.intersect = function (csg) {
  57853. var a = new Node(this.clone().polygons);
  57854. var b = new Node(csg.clone().polygons);
  57855. a.invert();
  57856. b.clipTo(a);
  57857. b.invert();
  57858. a.clipTo(b);
  57859. b.clipTo(a);
  57860. a.build(b.allPolygons());
  57861. a.invert();
  57862. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57863. };
  57864. CSG.prototype.intersectInPlace = function (csg) {
  57865. var a = new Node(this.polygons);
  57866. var b = new Node(csg.polygons);
  57867. a.invert();
  57868. b.clipTo(a);
  57869. b.invert();
  57870. a.clipTo(b);
  57871. b.clipTo(a);
  57872. a.build(b.allPolygons());
  57873. a.invert();
  57874. this.polygons = a.allPolygons();
  57875. };
  57876. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  57877. // not modified.
  57878. CSG.prototype.inverse = function () {
  57879. var csg = this.clone();
  57880. csg.inverseInPlace();
  57881. return csg;
  57882. };
  57883. CSG.prototype.inverseInPlace = function () {
  57884. this.polygons.map(function (p) { p.flip(); });
  57885. };
  57886. // This is used to keep meshes transformations so they can be restored
  57887. // when we build back a Babylon Mesh
  57888. // NB : All CSG operations are performed in world coordinates
  57889. CSG.prototype.copyTransformAttributes = function (csg) {
  57890. this.matrix = csg.matrix;
  57891. this.position = csg.position;
  57892. this.rotation = csg.rotation;
  57893. this.scaling = csg.scaling;
  57894. this.rotationQuaternion = csg.rotationQuaternion;
  57895. return this;
  57896. };
  57897. // Build Raw mesh from CSG
  57898. // Coordinates here are in world space
  57899. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  57900. var matrix = this.matrix.clone();
  57901. matrix.invert();
  57902. 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;
  57903. if (keepSubMeshes) {
  57904. // Sort Polygons, since subMeshes are indices range
  57905. polygons.sort(function (a, b) {
  57906. if (a.shared.meshId === b.shared.meshId) {
  57907. return a.shared.subMeshId - b.shared.subMeshId;
  57908. }
  57909. else {
  57910. return a.shared.meshId - b.shared.meshId;
  57911. }
  57912. });
  57913. }
  57914. for (var i = 0, il = polygons.length; i < il; i++) {
  57915. polygon = polygons[i];
  57916. // Building SubMeshes
  57917. if (!subMesh_dict[polygon.shared.meshId]) {
  57918. subMesh_dict[polygon.shared.meshId] = {};
  57919. }
  57920. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  57921. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  57922. indexStart: +Infinity,
  57923. indexEnd: -Infinity,
  57924. materialIndex: polygon.shared.materialIndex
  57925. };
  57926. }
  57927. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  57928. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  57929. polygonIndices[0] = 0;
  57930. polygonIndices[1] = j - 1;
  57931. polygonIndices[2] = j;
  57932. for (var k = 0; k < 3; k++) {
  57933. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  57934. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  57935. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  57936. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  57937. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  57938. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  57939. // Check if 2 points can be merged
  57940. if (!(typeof vertex_idx !== 'undefined' &&
  57941. normals[vertex_idx * 3] === localNormal.x &&
  57942. normals[vertex_idx * 3 + 1] === localNormal.y &&
  57943. normals[vertex_idx * 3 + 2] === localNormal.z &&
  57944. uvs[vertex_idx * 2] === uv.x &&
  57945. uvs[vertex_idx * 2 + 1] === uv.y)) {
  57946. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  57947. uvs.push(uv.x, uv.y);
  57948. normals.push(normal.x, normal.y, normal.z);
  57949. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  57950. }
  57951. indices.push(vertex_idx);
  57952. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  57953. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  57954. currentIndex++;
  57955. }
  57956. }
  57957. }
  57958. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  57959. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  57960. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  57961. mesh.setIndices(indices);
  57962. if (keepSubMeshes) {
  57963. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  57964. var materialIndexOffset = 0, materialMaxIndex;
  57965. mesh.subMeshes = new Array();
  57966. for (var m in subMesh_dict) {
  57967. materialMaxIndex = -1;
  57968. for (var sm in subMesh_dict[m]) {
  57969. subMesh_obj = subMesh_dict[m][sm];
  57970. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  57971. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  57972. }
  57973. materialIndexOffset += ++materialMaxIndex;
  57974. }
  57975. }
  57976. return mesh;
  57977. };
  57978. // Build Mesh from CSG taking material and transforms into account
  57979. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  57980. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  57981. mesh.material = material;
  57982. mesh.position.copyFrom(this.position);
  57983. mesh.rotation.copyFrom(this.rotation);
  57984. if (this.rotationQuaternion) {
  57985. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  57986. }
  57987. mesh.scaling.copyFrom(this.scaling);
  57988. mesh.computeWorldMatrix(true);
  57989. return mesh;
  57990. };
  57991. return CSG;
  57992. }());
  57993. BABYLON.CSG = CSG;
  57994. })(BABYLON || (BABYLON = {}));
  57995. //# sourceMappingURL=babylon.csg.js.map
  57996. var BABYLON;
  57997. (function (BABYLON) {
  57998. var LensFlare = (function () {
  57999. function LensFlare(size, position, color, imgUrl, system) {
  58000. this.size = size;
  58001. this.position = position;
  58002. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  58003. this.dispose = function () {
  58004. if (this.texture) {
  58005. this.texture.dispose();
  58006. }
  58007. // Remove from scene
  58008. var index = this._system.lensFlares.indexOf(this);
  58009. this._system.lensFlares.splice(index, 1);
  58010. };
  58011. this.color = color || new BABYLON.Color3(1, 1, 1);
  58012. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  58013. this._system = system;
  58014. system.lensFlares.push(this);
  58015. }
  58016. return LensFlare;
  58017. }());
  58018. BABYLON.LensFlare = LensFlare;
  58019. })(BABYLON || (BABYLON = {}));
  58020. //# sourceMappingURL=babylon.lensFlare.js.map
  58021. var BABYLON;
  58022. (function (BABYLON) {
  58023. var LensFlareSystem = (function () {
  58024. function LensFlareSystem(name, emitter, scene) {
  58025. this.name = name;
  58026. this.lensFlares = new Array();
  58027. this.borderLimit = 300;
  58028. this.viewportBorder = 0;
  58029. this.layerMask = 0x0FFFFFFF;
  58030. this._vertexBuffers = {};
  58031. this._isEnabled = true;
  58032. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58033. this._emitter = emitter;
  58034. this.id = name;
  58035. scene.lensFlareSystems.push(this);
  58036. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  58037. var engine = scene.getEngine();
  58038. // VBO
  58039. var vertices = [];
  58040. vertices.push(1, 1);
  58041. vertices.push(-1, 1);
  58042. vertices.push(-1, -1);
  58043. vertices.push(1, -1);
  58044. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  58045. // Indices
  58046. var indices = [];
  58047. indices.push(0);
  58048. indices.push(1);
  58049. indices.push(2);
  58050. indices.push(0);
  58051. indices.push(2);
  58052. indices.push(3);
  58053. this._indexBuffer = engine.createIndexBuffer(indices);
  58054. // Effects
  58055. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  58056. }
  58057. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  58058. get: function () {
  58059. return this._isEnabled;
  58060. },
  58061. set: function (value) {
  58062. this._isEnabled = value;
  58063. },
  58064. enumerable: true,
  58065. configurable: true
  58066. });
  58067. LensFlareSystem.prototype.getScene = function () {
  58068. return this._scene;
  58069. };
  58070. LensFlareSystem.prototype.getEmitter = function () {
  58071. return this._emitter;
  58072. };
  58073. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  58074. this._emitter = newEmitter;
  58075. };
  58076. LensFlareSystem.prototype.getEmitterPosition = function () {
  58077. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  58078. };
  58079. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  58080. var position = this.getEmitterPosition();
  58081. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  58082. this._positionX = position.x;
  58083. this._positionY = position.y;
  58084. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  58085. if (this.viewportBorder > 0) {
  58086. globalViewport.x -= this.viewportBorder;
  58087. globalViewport.y -= this.viewportBorder;
  58088. globalViewport.width += this.viewportBorder * 2;
  58089. globalViewport.height += this.viewportBorder * 2;
  58090. position.x += this.viewportBorder;
  58091. position.y += this.viewportBorder;
  58092. this._positionX += this.viewportBorder;
  58093. this._positionY += this.viewportBorder;
  58094. }
  58095. if (position.z > 0) {
  58096. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  58097. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  58098. return true;
  58099. }
  58100. return true;
  58101. }
  58102. return false;
  58103. };
  58104. LensFlareSystem.prototype._isVisible = function () {
  58105. if (!this._isEnabled) {
  58106. return false;
  58107. }
  58108. var emitterPosition = this.getEmitterPosition();
  58109. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  58110. var distance = direction.length();
  58111. direction.normalize();
  58112. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  58113. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  58114. return !pickInfo.hit || pickInfo.distance > distance;
  58115. };
  58116. LensFlareSystem.prototype.render = function () {
  58117. if (!this._effect.isReady())
  58118. return false;
  58119. var engine = this._scene.getEngine();
  58120. var viewport = this._scene.activeCamera.viewport;
  58121. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  58122. // Position
  58123. if (!this.computeEffectivePosition(globalViewport)) {
  58124. return false;
  58125. }
  58126. // Visibility
  58127. if (!this._isVisible()) {
  58128. return false;
  58129. }
  58130. // Intensity
  58131. var awayX;
  58132. var awayY;
  58133. if (this._positionX < this.borderLimit + globalViewport.x) {
  58134. awayX = this.borderLimit + globalViewport.x - this._positionX;
  58135. }
  58136. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  58137. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  58138. }
  58139. else {
  58140. awayX = 0;
  58141. }
  58142. if (this._positionY < this.borderLimit + globalViewport.y) {
  58143. awayY = this.borderLimit + globalViewport.y - this._positionY;
  58144. }
  58145. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  58146. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  58147. }
  58148. else {
  58149. awayY = 0;
  58150. }
  58151. var away = (awayX > awayY) ? awayX : awayY;
  58152. away -= this.viewportBorder;
  58153. if (away > this.borderLimit) {
  58154. away = this.borderLimit;
  58155. }
  58156. var intensity = 1.0 - (away / this.borderLimit);
  58157. if (intensity < 0) {
  58158. return false;
  58159. }
  58160. if (intensity > 1.0) {
  58161. intensity = 1.0;
  58162. }
  58163. if (this.viewportBorder > 0) {
  58164. globalViewport.x += this.viewportBorder;
  58165. globalViewport.y += this.viewportBorder;
  58166. globalViewport.width -= this.viewportBorder * 2;
  58167. globalViewport.height -= this.viewportBorder * 2;
  58168. this._positionX -= this.viewportBorder;
  58169. this._positionY -= this.viewportBorder;
  58170. }
  58171. // Position
  58172. var centerX = globalViewport.x + globalViewport.width / 2;
  58173. var centerY = globalViewport.y + globalViewport.height / 2;
  58174. var distX = centerX - this._positionX;
  58175. var distY = centerY - this._positionY;
  58176. // Effects
  58177. engine.enableEffect(this._effect);
  58178. engine.setState(false);
  58179. engine.setDepthBuffer(false);
  58180. // VBOs
  58181. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58182. // Flares
  58183. for (var index = 0; index < this.lensFlares.length; index++) {
  58184. var flare = this.lensFlares[index];
  58185. engine.setAlphaMode(flare.alphaMode);
  58186. var x = centerX - (distX * flare.position);
  58187. var y = centerY - (distY * flare.position);
  58188. var cw = flare.size;
  58189. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  58190. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  58191. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  58192. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  58193. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  58194. // Texture
  58195. this._effect.setTexture("textureSampler", flare.texture);
  58196. // Color
  58197. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  58198. // Draw order
  58199. engine.draw(true, 0, 6);
  58200. }
  58201. engine.setDepthBuffer(true);
  58202. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58203. return true;
  58204. };
  58205. LensFlareSystem.prototype.dispose = function () {
  58206. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58207. if (vertexBuffer) {
  58208. vertexBuffer.dispose();
  58209. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  58210. }
  58211. if (this._indexBuffer) {
  58212. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58213. this._indexBuffer = null;
  58214. }
  58215. while (this.lensFlares.length) {
  58216. this.lensFlares[0].dispose();
  58217. }
  58218. // Remove from scene
  58219. var index = this._scene.lensFlareSystems.indexOf(this);
  58220. this._scene.lensFlareSystems.splice(index, 1);
  58221. };
  58222. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  58223. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  58224. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  58225. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  58226. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  58227. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  58228. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  58229. var parsedFlare = parsedLensFlareSystem.flares[index];
  58230. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  58231. }
  58232. return lensFlareSystem;
  58233. };
  58234. LensFlareSystem.prototype.serialize = function () {
  58235. var serializationObject = {};
  58236. serializationObject.id = this.id;
  58237. serializationObject.name = this.name;
  58238. serializationObject.emitterId = this.getEmitter().id;
  58239. serializationObject.borderLimit = this.borderLimit;
  58240. serializationObject.flares = [];
  58241. for (var index = 0; index < this.lensFlares.length; index++) {
  58242. var flare = this.lensFlares[index];
  58243. serializationObject.flares.push({
  58244. size: flare.size,
  58245. position: flare.position,
  58246. color: flare.color.asArray(),
  58247. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  58248. });
  58249. }
  58250. return serializationObject;
  58251. };
  58252. return LensFlareSystem;
  58253. }());
  58254. BABYLON.LensFlareSystem = LensFlareSystem;
  58255. })(BABYLON || (BABYLON = {}));
  58256. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  58257. var BABYLON;
  58258. (function (BABYLON) {
  58259. /**
  58260. * This is a holder class for the physics joint created by the physics plugin.
  58261. * It holds a set of functions to control the underlying joint.
  58262. */
  58263. var PhysicsJoint = (function () {
  58264. function PhysicsJoint(type, jointData) {
  58265. this.type = type;
  58266. this.jointData = jointData;
  58267. jointData.nativeParams = jointData.nativeParams || {};
  58268. }
  58269. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  58270. get: function () {
  58271. return this._physicsJoint;
  58272. },
  58273. set: function (newJoint) {
  58274. if (this._physicsJoint) {
  58275. //remove from the wolrd
  58276. }
  58277. this._physicsJoint = newJoint;
  58278. },
  58279. enumerable: true,
  58280. configurable: true
  58281. });
  58282. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  58283. set: function (physicsPlugin) {
  58284. this._physicsPlugin = physicsPlugin;
  58285. },
  58286. enumerable: true,
  58287. configurable: true
  58288. });
  58289. /**
  58290. * Execute a function that is physics-plugin specific.
  58291. * @param {Function} func the function that will be executed.
  58292. * It accepts two parameters: the physics world and the physics joint.
  58293. */
  58294. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  58295. func(this._physicsPlugin.world, this._physicsJoint);
  58296. };
  58297. return PhysicsJoint;
  58298. }());
  58299. //TODO check if the native joints are the same
  58300. //Joint Types
  58301. PhysicsJoint.DistanceJoint = 0;
  58302. PhysicsJoint.HingeJoint = 1;
  58303. PhysicsJoint.BallAndSocketJoint = 2;
  58304. PhysicsJoint.WheelJoint = 3;
  58305. PhysicsJoint.SliderJoint = 4;
  58306. //OIMO
  58307. PhysicsJoint.PrismaticJoint = 5;
  58308. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  58309. PhysicsJoint.UniversalJoint = 6;
  58310. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  58311. //Cannon
  58312. //Similar to a Ball-Joint. Different in params
  58313. PhysicsJoint.PointToPointJoint = 8;
  58314. //Cannon only at the moment
  58315. PhysicsJoint.SpringJoint = 9;
  58316. PhysicsJoint.LockJoint = 10;
  58317. BABYLON.PhysicsJoint = PhysicsJoint;
  58318. /**
  58319. * A class representing a physics distance joint.
  58320. */
  58321. var DistanceJoint = (function (_super) {
  58322. __extends(DistanceJoint, _super);
  58323. function DistanceJoint(jointData) {
  58324. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  58325. }
  58326. /**
  58327. * Update the predefined distance.
  58328. */
  58329. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  58330. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  58331. };
  58332. return DistanceJoint;
  58333. }(PhysicsJoint));
  58334. BABYLON.DistanceJoint = DistanceJoint;
  58335. var MotorEnabledJoint = (function (_super) {
  58336. __extends(MotorEnabledJoint, _super);
  58337. function MotorEnabledJoint(type, jointData) {
  58338. return _super.call(this, type, jointData) || this;
  58339. }
  58340. /**
  58341. * Set the motor values.
  58342. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58343. * @param {number} force the force to apply
  58344. * @param {number} maxForce max force for this motor.
  58345. */
  58346. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  58347. this._physicsPlugin.setMotor(this, force, maxForce);
  58348. };
  58349. /**
  58350. * Set the motor's limits.
  58351. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58352. */
  58353. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  58354. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  58355. };
  58356. return MotorEnabledJoint;
  58357. }(PhysicsJoint));
  58358. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  58359. /**
  58360. * This class represents a single hinge physics joint
  58361. */
  58362. var HingeJoint = (function (_super) {
  58363. __extends(HingeJoint, _super);
  58364. function HingeJoint(jointData) {
  58365. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  58366. }
  58367. /**
  58368. * Set the motor values.
  58369. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58370. * @param {number} force the force to apply
  58371. * @param {number} maxForce max force for this motor.
  58372. */
  58373. HingeJoint.prototype.setMotor = function (force, maxForce) {
  58374. this._physicsPlugin.setMotor(this, force, maxForce);
  58375. };
  58376. /**
  58377. * Set the motor's limits.
  58378. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58379. */
  58380. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  58381. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  58382. };
  58383. return HingeJoint;
  58384. }(MotorEnabledJoint));
  58385. BABYLON.HingeJoint = HingeJoint;
  58386. /**
  58387. * This class represents a dual hinge physics joint (same as wheel joint)
  58388. */
  58389. var Hinge2Joint = (function (_super) {
  58390. __extends(Hinge2Joint, _super);
  58391. function Hinge2Joint(jointData) {
  58392. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  58393. }
  58394. /**
  58395. * Set the motor values.
  58396. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58397. * @param {number} force the force to apply
  58398. * @param {number} maxForce max force for this motor.
  58399. * @param {motorIndex} the motor's index, 0 or 1.
  58400. */
  58401. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  58402. if (motorIndex === void 0) { motorIndex = 0; }
  58403. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  58404. };
  58405. /**
  58406. * Set the motor limits.
  58407. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58408. * @param {number} upperLimit the upper limit
  58409. * @param {number} lowerLimit lower limit
  58410. * @param {motorIndex} the motor's index, 0 or 1.
  58411. */
  58412. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  58413. if (motorIndex === void 0) { motorIndex = 0; }
  58414. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  58415. };
  58416. return Hinge2Joint;
  58417. }(MotorEnabledJoint));
  58418. BABYLON.Hinge2Joint = Hinge2Joint;
  58419. })(BABYLON || (BABYLON = {}));
  58420. //# sourceMappingURL=babylon.physicsJoint.js.map
  58421. var BABYLON;
  58422. (function (BABYLON) {
  58423. var PhysicsImpostor = (function () {
  58424. function PhysicsImpostor(object, type, _options, _scene) {
  58425. if (_options === void 0) { _options = { mass: 0 }; }
  58426. var _this = this;
  58427. this.object = object;
  58428. this.type = type;
  58429. this._options = _options;
  58430. this._scene = _scene;
  58431. this._bodyUpdateRequired = false;
  58432. this._onBeforePhysicsStepCallbacks = new Array();
  58433. this._onAfterPhysicsStepCallbacks = new Array();
  58434. this._onPhysicsCollideCallbacks = [];
  58435. this._deltaPosition = BABYLON.Vector3.Zero();
  58436. this._isDisposed = false;
  58437. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  58438. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  58439. /**
  58440. * this function is executed by the physics engine.
  58441. */
  58442. this.beforeStep = function () {
  58443. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  58444. //conjugate deltaRotation
  58445. if (_this._deltaRotationConjugated) {
  58446. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  58447. }
  58448. else {
  58449. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  58450. }
  58451. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  58452. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  58453. func(_this);
  58454. });
  58455. };
  58456. /**
  58457. * this function is executed by the physics engine.
  58458. */
  58459. this.afterStep = function () {
  58460. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  58461. func(_this);
  58462. });
  58463. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  58464. _this.object.position.addInPlace(_this._deltaPosition);
  58465. if (_this._deltaRotation) {
  58466. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  58467. }
  58468. };
  58469. /**
  58470. * Legacy collision detection event support
  58471. */
  58472. this.onCollideEvent = null;
  58473. //event and body object due to cannon's event-based architecture.
  58474. this.onCollide = function (e) {
  58475. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  58476. return;
  58477. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  58478. if (otherImpostor) {
  58479. // Legacy collision detection event support
  58480. if (_this.onCollideEvent) {
  58481. _this.onCollideEvent(_this, otherImpostor);
  58482. }
  58483. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  58484. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  58485. }).forEach(function (obj) {
  58486. obj.callback(_this, otherImpostor);
  58487. });
  58488. }
  58489. };
  58490. //sanity check!
  58491. if (!this.object) {
  58492. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  58493. return;
  58494. }
  58495. //legacy support for old syntax.
  58496. if (!this._scene && object.getScene) {
  58497. this._scene = object.getScene();
  58498. }
  58499. this._physicsEngine = this._scene.getPhysicsEngine();
  58500. if (!this._physicsEngine) {
  58501. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  58502. }
  58503. else {
  58504. //set the object's quaternion, if not set
  58505. if (!this.object.rotationQuaternion) {
  58506. if (this.object.rotation) {
  58507. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  58508. }
  58509. else {
  58510. this.object.rotationQuaternion = new BABYLON.Quaternion();
  58511. }
  58512. }
  58513. //default options params
  58514. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  58515. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  58516. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  58517. this._joints = [];
  58518. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  58519. if (!this.object.parent) {
  58520. this._init();
  58521. }
  58522. else if (this.object.parent.physicsImpostor) {
  58523. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  58524. }
  58525. }
  58526. }
  58527. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  58528. get: function () {
  58529. return this._isDisposed;
  58530. },
  58531. enumerable: true,
  58532. configurable: true
  58533. });
  58534. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  58535. get: function () {
  58536. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  58537. },
  58538. set: function (value) {
  58539. this.setMass(value);
  58540. },
  58541. enumerable: true,
  58542. configurable: true
  58543. });
  58544. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  58545. get: function () {
  58546. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  58547. },
  58548. set: function (value) {
  58549. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  58550. },
  58551. enumerable: true,
  58552. configurable: true
  58553. });
  58554. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  58555. get: function () {
  58556. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  58557. },
  58558. set: function (value) {
  58559. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  58560. },
  58561. enumerable: true,
  58562. configurable: true
  58563. });
  58564. /**
  58565. * This function will completly initialize this impostor.
  58566. * It will create a new body - but only if this mesh has no parent.
  58567. * If it has, this impostor will not be used other than to define the impostor
  58568. * of the child mesh.
  58569. */
  58570. PhysicsImpostor.prototype._init = function () {
  58571. this._physicsEngine.removeImpostor(this);
  58572. this.physicsBody = null;
  58573. this._parent = this._parent || this._getPhysicsParent();
  58574. if (!this.parent) {
  58575. this._physicsEngine.addImpostor(this);
  58576. }
  58577. };
  58578. PhysicsImpostor.prototype._getPhysicsParent = function () {
  58579. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  58580. var parentMesh = this.object.parent;
  58581. return parentMesh.physicsImpostor;
  58582. }
  58583. return;
  58584. };
  58585. /**
  58586. * Should a new body be generated.
  58587. */
  58588. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  58589. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  58590. };
  58591. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  58592. this.forceUpdate();
  58593. };
  58594. /**
  58595. * Force a regeneration of this or the parent's impostor's body.
  58596. * Use under cautious - This will remove all joints already implemented.
  58597. */
  58598. PhysicsImpostor.prototype.forceUpdate = function () {
  58599. this._init();
  58600. if (this.parent) {
  58601. this.parent.forceUpdate();
  58602. }
  58603. };
  58604. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  58605. /*public get mesh(): AbstractMesh {
  58606. return this._mesh;
  58607. }*/
  58608. /**
  58609. * Gets the body that holds this impostor. Either its own, or its parent.
  58610. */
  58611. get: function () {
  58612. return this._parent ? this._parent.physicsBody : this._physicsBody;
  58613. },
  58614. /**
  58615. * Set the physics body. Used mainly by the physics engine/plugin
  58616. */
  58617. set: function (physicsBody) {
  58618. if (this._physicsBody) {
  58619. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  58620. }
  58621. this._physicsBody = physicsBody;
  58622. this.resetUpdateFlags();
  58623. },
  58624. enumerable: true,
  58625. configurable: true
  58626. });
  58627. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  58628. get: function () {
  58629. return this._parent;
  58630. },
  58631. set: function (value) {
  58632. this._parent = value;
  58633. },
  58634. enumerable: true,
  58635. configurable: true
  58636. });
  58637. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  58638. this._bodyUpdateRequired = false;
  58639. };
  58640. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  58641. if (this.object.getBoundingInfo) {
  58642. var q = this.object.rotationQuaternion;
  58643. //reset rotation
  58644. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  58645. //calculate the world matrix with no rotation
  58646. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  58647. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  58648. //bring back the rotation
  58649. this.object.rotationQuaternion = q;
  58650. //calculate the world matrix with the new rotation
  58651. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  58652. return size;
  58653. }
  58654. else {
  58655. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  58656. }
  58657. };
  58658. PhysicsImpostor.prototype.getObjectCenter = function () {
  58659. if (this.object.getBoundingInfo) {
  58660. return this.object.getBoundingInfo().boundingBox.centerWorld;
  58661. }
  58662. else {
  58663. return this.object.position;
  58664. }
  58665. };
  58666. /**
  58667. * Get a specific parametes from the options parameter.
  58668. */
  58669. PhysicsImpostor.prototype.getParam = function (paramName) {
  58670. return this._options[paramName];
  58671. };
  58672. /**
  58673. * Sets a specific parameter in the options given to the physics plugin
  58674. */
  58675. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  58676. this._options[paramName] = value;
  58677. this._bodyUpdateRequired = true;
  58678. };
  58679. /**
  58680. * Specifically change the body's mass option. Won't recreate the physics body object
  58681. */
  58682. PhysicsImpostor.prototype.setMass = function (mass) {
  58683. if (this.getParam("mass") !== mass) {
  58684. this.setParam("mass", mass);
  58685. }
  58686. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  58687. };
  58688. PhysicsImpostor.prototype.getLinearVelocity = function () {
  58689. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  58690. };
  58691. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  58692. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  58693. };
  58694. PhysicsImpostor.prototype.getAngularVelocity = function () {
  58695. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  58696. };
  58697. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  58698. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  58699. };
  58700. /**
  58701. * Execute a function with the physics plugin native code.
  58702. * Provide a function the will have two variables - the world object and the physics body object.
  58703. */
  58704. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  58705. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  58706. };
  58707. /**
  58708. * Register a function that will be executed before the physics world is stepping forward.
  58709. */
  58710. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  58711. this._onBeforePhysicsStepCallbacks.push(func);
  58712. };
  58713. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  58714. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  58715. if (index > -1) {
  58716. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  58717. }
  58718. else {
  58719. BABYLON.Tools.Warn("Function to remove was not found");
  58720. }
  58721. };
  58722. /**
  58723. * Register a function that will be executed after the physics step
  58724. */
  58725. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  58726. this._onAfterPhysicsStepCallbacks.push(func);
  58727. };
  58728. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  58729. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  58730. if (index > -1) {
  58731. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  58732. }
  58733. else {
  58734. BABYLON.Tools.Warn("Function to remove was not found");
  58735. }
  58736. };
  58737. /**
  58738. * register a function that will be executed when this impostor collides against a different body.
  58739. */
  58740. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  58741. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  58742. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  58743. };
  58744. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  58745. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  58746. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  58747. if (index > -1) {
  58748. this._onPhysicsCollideCallbacks.splice(index, 1);
  58749. }
  58750. else {
  58751. BABYLON.Tools.Warn("Function to remove was not found");
  58752. }
  58753. };
  58754. /**
  58755. * Apply a force
  58756. */
  58757. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  58758. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  58759. };
  58760. /**
  58761. * Apply an impulse
  58762. */
  58763. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  58764. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  58765. };
  58766. /**
  58767. * A help function to create a joint.
  58768. */
  58769. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  58770. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  58771. this.addJoint(otherImpostor, joint);
  58772. };
  58773. /**
  58774. * Add a joint to this impostor with a different impostor.
  58775. */
  58776. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  58777. this._joints.push({
  58778. otherImpostor: otherImpostor,
  58779. joint: joint
  58780. });
  58781. this._physicsEngine.addJoint(this, otherImpostor, joint);
  58782. };
  58783. /**
  58784. * Will keep this body still, in a sleep mode.
  58785. */
  58786. PhysicsImpostor.prototype.sleep = function () {
  58787. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  58788. };
  58789. /**
  58790. * Wake the body up.
  58791. */
  58792. PhysicsImpostor.prototype.wakeUp = function () {
  58793. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  58794. };
  58795. PhysicsImpostor.prototype.clone = function (newObject) {
  58796. if (!newObject)
  58797. return null;
  58798. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  58799. };
  58800. PhysicsImpostor.prototype.dispose = function () {
  58801. var _this = this;
  58802. //no dispose if no physics engine is available.
  58803. if (!this._physicsEngine) {
  58804. return;
  58805. }
  58806. this._joints.forEach(function (j) {
  58807. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  58808. });
  58809. //dispose the physics body
  58810. this._physicsEngine.removeImpostor(this);
  58811. if (this.parent) {
  58812. this.parent.forceUpdate();
  58813. }
  58814. else {
  58815. /*this._object.getChildMeshes().forEach(function(mesh) {
  58816. if (mesh.physicsImpostor) {
  58817. if (disposeChildren) {
  58818. mesh.physicsImpostor.dispose();
  58819. mesh.physicsImpostor = null;
  58820. }
  58821. }
  58822. })*/
  58823. }
  58824. this._isDisposed = true;
  58825. };
  58826. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  58827. this._deltaPosition.copyFrom(position);
  58828. };
  58829. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  58830. if (!this._deltaRotation) {
  58831. this._deltaRotation = new BABYLON.Quaternion();
  58832. }
  58833. this._deltaRotation.copyFrom(rotation);
  58834. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  58835. };
  58836. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  58837. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  58838. };
  58839. PhysicsImpostor.prototype.getRadius = function () {
  58840. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  58841. };
  58842. /**
  58843. * Sync a bone with this impostor
  58844. * @param bone The bone to sync to the impostor.
  58845. * @param boneMesh The mesh that the bone is influencing.
  58846. * @param jointPivot The pivot of the joint / bone in local space.
  58847. * @param distToJoint Optional distance from the impostor to the joint.
  58848. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  58849. */
  58850. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  58851. var tempVec = PhysicsImpostor._tmpVecs[0];
  58852. var mesh = this.object;
  58853. if (adjustRotation) {
  58854. var tempQuat = PhysicsImpostor._tmpQuat;
  58855. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  58856. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  58857. }
  58858. else {
  58859. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  58860. }
  58861. tempVec.x = 0;
  58862. tempVec.y = 0;
  58863. tempVec.z = 0;
  58864. if (jointPivot) {
  58865. tempVec.x = jointPivot.x;
  58866. tempVec.y = jointPivot.y;
  58867. tempVec.z = jointPivot.z;
  58868. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  58869. if (distToJoint === undefined || distToJoint === null) {
  58870. distToJoint = jointPivot.length();
  58871. }
  58872. tempVec.x *= distToJoint;
  58873. tempVec.y *= distToJoint;
  58874. tempVec.z *= distToJoint;
  58875. }
  58876. if (bone.getParent()) {
  58877. tempVec.addInPlace(mesh.getAbsolutePosition());
  58878. bone.setAbsolutePosition(tempVec, boneMesh);
  58879. }
  58880. else {
  58881. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  58882. boneMesh.position.x -= tempVec.x;
  58883. boneMesh.position.y -= tempVec.y;
  58884. boneMesh.position.z -= tempVec.z;
  58885. }
  58886. };
  58887. /**
  58888. * Sync impostor to a bone
  58889. * @param bone The bone that the impostor will be synced to.
  58890. * @param boneMesh The mesh that the bone is influencing.
  58891. * @param jointPivot The pivot of the joint / bone in local space.
  58892. * @param distToJoint Optional distance from the impostor to the joint.
  58893. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  58894. * @param boneAxis Optional vector3 axis the bone is aligned with
  58895. */
  58896. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  58897. var mesh = this.object;
  58898. if (adjustRotation) {
  58899. var tempQuat = PhysicsImpostor._tmpQuat;
  58900. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  58901. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  58902. }
  58903. else {
  58904. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  58905. }
  58906. var pos = PhysicsImpostor._tmpVecs[0];
  58907. var boneDir = PhysicsImpostor._tmpVecs[1];
  58908. if (!boneAxis) {
  58909. boneAxis = PhysicsImpostor._tmpVecs[2];
  58910. boneAxis.x = 0;
  58911. boneAxis.y = 1;
  58912. boneAxis.z = 0;
  58913. }
  58914. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  58915. bone.getAbsolutePositionToRef(boneMesh, pos);
  58916. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  58917. distToJoint = jointPivot.length();
  58918. }
  58919. if (distToJoint !== undefined && distToJoint !== null) {
  58920. pos.x += boneDir.x * distToJoint;
  58921. pos.y += boneDir.y * distToJoint;
  58922. pos.z += boneDir.z * distToJoint;
  58923. }
  58924. mesh.setAbsolutePosition(pos);
  58925. };
  58926. return PhysicsImpostor;
  58927. }());
  58928. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  58929. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  58930. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58931. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  58932. //Impostor types
  58933. PhysicsImpostor.NoImpostor = 0;
  58934. PhysicsImpostor.SphereImpostor = 1;
  58935. PhysicsImpostor.BoxImpostor = 2;
  58936. PhysicsImpostor.PlaneImpostor = 3;
  58937. PhysicsImpostor.MeshImpostor = 4;
  58938. PhysicsImpostor.CylinderImpostor = 7;
  58939. PhysicsImpostor.ParticleImpostor = 8;
  58940. PhysicsImpostor.HeightmapImpostor = 9;
  58941. BABYLON.PhysicsImpostor = PhysicsImpostor;
  58942. })(BABYLON || (BABYLON = {}));
  58943. //# sourceMappingURL=babylon.physicsImpostor.js.map
  58944. var BABYLON;
  58945. (function (BABYLON) {
  58946. var PhysicsEngine = (function () {
  58947. function PhysicsEngine(gravity, _physicsPlugin) {
  58948. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  58949. this._physicsPlugin = _physicsPlugin;
  58950. //new methods and parameters
  58951. this._impostors = [];
  58952. this._joints = [];
  58953. if (!this._physicsPlugin.isSupported()) {
  58954. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  58955. + "Please make sure it is included.");
  58956. }
  58957. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  58958. this.setGravity(gravity);
  58959. this.setTimeStep();
  58960. }
  58961. PhysicsEngine.prototype.setGravity = function (gravity) {
  58962. this.gravity = gravity;
  58963. this._physicsPlugin.setGravity(this.gravity);
  58964. };
  58965. /**
  58966. * Set the time step of the physics engine.
  58967. * default is 1/60.
  58968. * To slow it down, enter 1/600 for example.
  58969. * To speed it up, 1/30
  58970. * @param {number} newTimeStep the new timestep to apply to this world.
  58971. */
  58972. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  58973. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  58974. this._physicsPlugin.setTimeStep(newTimeStep);
  58975. };
  58976. PhysicsEngine.prototype.dispose = function () {
  58977. this._impostors.forEach(function (impostor) {
  58978. impostor.dispose();
  58979. });
  58980. this._physicsPlugin.dispose();
  58981. };
  58982. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  58983. return this._physicsPlugin.name;
  58984. };
  58985. /**
  58986. * Adding a new impostor for the impostor tracking.
  58987. * This will be done by the impostor itself.
  58988. * @param {PhysicsImpostor} impostor the impostor to add
  58989. */
  58990. PhysicsEngine.prototype.addImpostor = function (impostor) {
  58991. impostor.uniqueId = this._impostors.push(impostor);
  58992. //if no parent, generate the body
  58993. if (!impostor.parent) {
  58994. this._physicsPlugin.generatePhysicsBody(impostor);
  58995. }
  58996. };
  58997. /**
  58998. * Remove an impostor from the engine.
  58999. * This impostor and its mesh will not longer be updated by the physics engine.
  59000. * @param {PhysicsImpostor} impostor the impostor to remove
  59001. */
  59002. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  59003. var index = this._impostors.indexOf(impostor);
  59004. if (index > -1) {
  59005. var removed = this._impostors.splice(index, 1);
  59006. //Is it needed?
  59007. if (removed.length) {
  59008. //this will also remove it from the world.
  59009. removed[0].physicsBody = null;
  59010. }
  59011. }
  59012. };
  59013. /**
  59014. * Add a joint to the physics engine
  59015. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  59016. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  59017. * @param {PhysicsJoint} the joint that will connect both impostors.
  59018. */
  59019. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  59020. var impostorJoint = {
  59021. mainImpostor: mainImpostor,
  59022. connectedImpostor: connectedImpostor,
  59023. joint: joint
  59024. };
  59025. joint.physicsPlugin = this._physicsPlugin;
  59026. this._joints.push(impostorJoint);
  59027. this._physicsPlugin.generateJoint(impostorJoint);
  59028. };
  59029. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  59030. var matchingJoints = this._joints.filter(function (impostorJoint) {
  59031. return (impostorJoint.connectedImpostor === connectedImpostor
  59032. && impostorJoint.joint === joint
  59033. && impostorJoint.mainImpostor === mainImpostor);
  59034. });
  59035. if (matchingJoints.length) {
  59036. this._physicsPlugin.removeJoint(matchingJoints[0]);
  59037. //TODO remove it from the list as well
  59038. }
  59039. };
  59040. /**
  59041. * Called by the scene. no need to call it.
  59042. */
  59043. PhysicsEngine.prototype._step = function (delta) {
  59044. var _this = this;
  59045. //check if any mesh has no body / requires an update
  59046. this._impostors.forEach(function (impostor) {
  59047. if (impostor.isBodyInitRequired()) {
  59048. _this._physicsPlugin.generatePhysicsBody(impostor);
  59049. }
  59050. });
  59051. if (delta > 0.1) {
  59052. delta = 0.1;
  59053. }
  59054. else if (delta <= 0) {
  59055. delta = 1.0 / 60.0;
  59056. }
  59057. this._physicsPlugin.executeStep(delta, this._impostors);
  59058. };
  59059. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  59060. return this._physicsPlugin;
  59061. };
  59062. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  59063. for (var i = 0; i < this._impostors.length; ++i) {
  59064. if (this._impostors[i].object === object) {
  59065. return this._impostors[i];
  59066. }
  59067. }
  59068. };
  59069. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  59070. for (var i = 0; i < this._impostors.length; ++i) {
  59071. if (this._impostors[i].physicsBody === body) {
  59072. return this._impostors[i];
  59073. }
  59074. }
  59075. };
  59076. return PhysicsEngine;
  59077. }());
  59078. // Statics
  59079. PhysicsEngine.Epsilon = 0.001;
  59080. BABYLON.PhysicsEngine = PhysicsEngine;
  59081. })(BABYLON || (BABYLON = {}));
  59082. //# sourceMappingURL=babylon.physicsEngine.js.map
  59083. var BABYLON;
  59084. (function (BABYLON) {
  59085. var CannonJSPlugin = (function () {
  59086. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  59087. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  59088. if (iterations === void 0) { iterations = 10; }
  59089. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  59090. this.name = "CannonJSPlugin";
  59091. this._physicsMaterials = [];
  59092. this._fixedTimeStep = 1 / 60;
  59093. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59094. this._currentCollisionGroup = 2;
  59095. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  59096. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  59097. this._tmpPosition = BABYLON.Vector3.Zero();
  59098. this._tmpQuaternion = new BABYLON.Quaternion();
  59099. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  59100. this._tmpDeltaRotation = new BABYLON.Quaternion();
  59101. this._tmpUnityRotation = new BABYLON.Quaternion();
  59102. if (!this.isSupported()) {
  59103. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  59104. return;
  59105. }
  59106. this.world = new CANNON.World();
  59107. this.world.broadphase = new CANNON.NaiveBroadphase();
  59108. this.world.solver.iterations = iterations;
  59109. }
  59110. CannonJSPlugin.prototype.setGravity = function (gravity) {
  59111. this.world.gravity.copy(gravity);
  59112. };
  59113. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  59114. this._fixedTimeStep = timeStep;
  59115. };
  59116. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  59117. // Delta is in seconds, should be provided in milliseconds
  59118. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  59119. };
  59120. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  59121. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59122. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59123. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  59124. };
  59125. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  59126. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59127. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59128. impostor.physicsBody.applyForce(impulse, worldPoint);
  59129. };
  59130. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  59131. //parent-child relationship. Does this impostor has a parent impostor?
  59132. if (impostor.parent) {
  59133. if (impostor.physicsBody) {
  59134. this.removePhysicsBody(impostor);
  59135. //TODO is that needed?
  59136. impostor.forceUpdate();
  59137. }
  59138. return;
  59139. }
  59140. //should a new body be created for this impostor?
  59141. if (impostor.isBodyInitRequired()) {
  59142. var shape = this._createShape(impostor);
  59143. //unregister events, if body is being changed
  59144. var oldBody = impostor.physicsBody;
  59145. if (oldBody) {
  59146. this.removePhysicsBody(impostor);
  59147. }
  59148. //create the body and material
  59149. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  59150. var bodyCreationObject = {
  59151. mass: impostor.getParam("mass"),
  59152. material: material
  59153. };
  59154. // A simple extend, in case native options were used.
  59155. var nativeOptions = impostor.getParam("nativeOptions");
  59156. for (var key in nativeOptions) {
  59157. if (nativeOptions.hasOwnProperty(key)) {
  59158. bodyCreationObject[key] = nativeOptions[key];
  59159. }
  59160. }
  59161. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  59162. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  59163. this.world.addEventListener("preStep", impostor.beforeStep);
  59164. this.world.addEventListener("postStep", impostor.afterStep);
  59165. impostor.physicsBody.addShape(shape);
  59166. this.world.add(impostor.physicsBody);
  59167. //try to keep the body moving in the right direction by taking old properties.
  59168. //Should be tested!
  59169. if (oldBody) {
  59170. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  59171. impostor.physicsBody[param].copy(oldBody[param]);
  59172. });
  59173. }
  59174. this._processChildMeshes(impostor);
  59175. }
  59176. //now update the body's transformation
  59177. this._updatePhysicsBodyTransformation(impostor);
  59178. };
  59179. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  59180. var _this = this;
  59181. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  59182. if (meshChildren.length) {
  59183. var processMesh = function (localPosition, mesh) {
  59184. var childImpostor = mesh.getPhysicsImpostor();
  59185. if (childImpostor) {
  59186. var parent = childImpostor.parent;
  59187. if (parent !== mainImpostor) {
  59188. var localPosition = mesh.position;
  59189. if (childImpostor.physicsBody) {
  59190. _this.removePhysicsBody(childImpostor);
  59191. childImpostor.physicsBody = null;
  59192. }
  59193. childImpostor.parent = mainImpostor;
  59194. childImpostor.resetUpdateFlags();
  59195. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  59196. //Add the mass of the children.
  59197. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  59198. }
  59199. }
  59200. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  59201. };
  59202. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  59203. }
  59204. };
  59205. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  59206. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  59207. this.world.removeEventListener("preStep", impostor.beforeStep);
  59208. this.world.removeEventListener("postStep", impostor.afterStep);
  59209. this.world.remove(impostor.physicsBody);
  59210. };
  59211. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  59212. var mainBody = impostorJoint.mainImpostor.physicsBody;
  59213. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  59214. if (!mainBody || !connectedBody) {
  59215. return;
  59216. }
  59217. var constraint;
  59218. var jointData = impostorJoint.joint.jointData;
  59219. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59220. var constraintData = {
  59221. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  59222. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  59223. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  59224. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  59225. maxForce: jointData.nativeParams.maxForce,
  59226. collideConnected: !!jointData.collision
  59227. };
  59228. switch (impostorJoint.joint.type) {
  59229. case BABYLON.PhysicsJoint.HingeJoint:
  59230. case BABYLON.PhysicsJoint.Hinge2Joint:
  59231. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  59232. break;
  59233. case BABYLON.PhysicsJoint.DistanceJoint:
  59234. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  59235. break;
  59236. case BABYLON.PhysicsJoint.SpringJoint:
  59237. var springData = jointData;
  59238. constraint = new CANNON.Spring(mainBody, connectedBody, {
  59239. restLength: springData.length,
  59240. stiffness: springData.stiffness,
  59241. damping: springData.damping,
  59242. localAnchorA: constraintData.pivotA,
  59243. localAnchorB: constraintData.pivotB
  59244. });
  59245. break;
  59246. case BABYLON.PhysicsJoint.LockJoint:
  59247. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  59248. break;
  59249. case BABYLON.PhysicsJoint.PointToPointJoint:
  59250. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  59251. default:
  59252. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  59253. break;
  59254. }
  59255. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  59256. constraint.collideConnected = !!jointData.collision;
  59257. impostorJoint.joint.physicsJoint = constraint;
  59258. //don't add spring as constraint, as it is not one.
  59259. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  59260. this.world.addConstraint(constraint);
  59261. }
  59262. else {
  59263. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  59264. constraint.applyForce();
  59265. });
  59266. }
  59267. };
  59268. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  59269. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  59270. };
  59271. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  59272. var index;
  59273. var mat;
  59274. for (index = 0; index < this._physicsMaterials.length; index++) {
  59275. mat = this._physicsMaterials[index];
  59276. if (mat.friction === friction && mat.restitution === restitution) {
  59277. return mat;
  59278. }
  59279. }
  59280. var currentMat = new CANNON.Material(name);
  59281. currentMat.friction = friction;
  59282. currentMat.restitution = restitution;
  59283. this._physicsMaterials.push(currentMat);
  59284. return currentMat;
  59285. };
  59286. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  59287. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  59288. };
  59289. CannonJSPlugin.prototype._createShape = function (impostor) {
  59290. var object = impostor.object;
  59291. var returnValue;
  59292. var extendSize = impostor.getObjectExtendSize();
  59293. switch (impostor.type) {
  59294. case BABYLON.PhysicsImpostor.SphereImpostor:
  59295. var radiusX = extendSize.x;
  59296. var radiusY = extendSize.y;
  59297. var radiusZ = extendSize.z;
  59298. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  59299. break;
  59300. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  59301. case BABYLON.PhysicsImpostor.CylinderImpostor:
  59302. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  59303. break;
  59304. case BABYLON.PhysicsImpostor.BoxImpostor:
  59305. var box = extendSize.scale(0.5);
  59306. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  59307. break;
  59308. case BABYLON.PhysicsImpostor.PlaneImpostor:
  59309. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  59310. returnValue = new CANNON.Plane();
  59311. break;
  59312. case BABYLON.PhysicsImpostor.MeshImpostor:
  59313. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  59314. var rawFaces = object.getIndices ? object.getIndices() : [];
  59315. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  59316. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  59317. break;
  59318. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  59319. returnValue = this._createHeightmap(object);
  59320. break;
  59321. case BABYLON.PhysicsImpostor.ParticleImpostor:
  59322. returnValue = new CANNON.Particle();
  59323. break;
  59324. }
  59325. return returnValue;
  59326. };
  59327. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  59328. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59329. var matrix = [];
  59330. //For now pointDepth will not be used and will be automatically calculated.
  59331. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  59332. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  59333. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  59334. var elementSize = dim * 2 / arraySize;
  59335. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  59336. for (var i = 0; i < pos.length; i = i + 3) {
  59337. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  59338. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  59339. var y = pos[i + 1] + minY;
  59340. if (!matrix[x]) {
  59341. matrix[x] = [];
  59342. }
  59343. if (!matrix[x][z]) {
  59344. matrix[x][z] = y;
  59345. }
  59346. matrix[x][z] = Math.max(y, matrix[x][z]);
  59347. }
  59348. for (var x = 0; x <= arraySize; ++x) {
  59349. if (!matrix[x]) {
  59350. var loc = 1;
  59351. while (!matrix[(x + loc) % arraySize]) {
  59352. loc++;
  59353. }
  59354. matrix[x] = matrix[(x + loc) % arraySize].slice();
  59355. //console.log("missing x", x);
  59356. }
  59357. for (var z = 0; z <= arraySize; ++z) {
  59358. if (!matrix[x][z]) {
  59359. var loc = 1;
  59360. var newValue;
  59361. while (newValue === undefined) {
  59362. newValue = matrix[x][(z + loc++) % arraySize];
  59363. }
  59364. matrix[x][z] = newValue;
  59365. }
  59366. }
  59367. }
  59368. var shape = new CANNON.Heightfield(matrix, {
  59369. elementSize: elementSize
  59370. });
  59371. //For future reference, needed for body transformation
  59372. shape.minY = minY;
  59373. return shape;
  59374. };
  59375. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  59376. var object = impostor.object;
  59377. //make sure it is updated...
  59378. object.computeWorldMatrix && object.computeWorldMatrix(true);
  59379. // The delta between the mesh position and the mesh bounding box center
  59380. var center = impostor.getObjectCenter();
  59381. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  59382. this._tmpPosition.copyFrom(center);
  59383. var quaternion = object.rotationQuaternion;
  59384. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  59385. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  59386. //-90 DEG in X, precalculated
  59387. quaternion = quaternion.multiply(this._minus90X);
  59388. //Invert! (Precalculated, 90 deg in X)
  59389. //No need to clone. this will never change.
  59390. impostor.setDeltaRotation(this._plus90X);
  59391. }
  59392. //If it is a heightfield, if should be centered.
  59393. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  59394. var mesh = object;
  59395. //calculate the correct body position:
  59396. var rotationQuaternion = mesh.rotationQuaternion;
  59397. mesh.rotationQuaternion = this._tmpUnityRotation;
  59398. mesh.computeWorldMatrix(true);
  59399. //get original center with no rotation
  59400. var c = center.clone();
  59401. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  59402. //rotation is back
  59403. mesh.rotationQuaternion = rotationQuaternion;
  59404. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  59405. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  59406. mesh.setPivotMatrix(p);
  59407. mesh.computeWorldMatrix(true);
  59408. //calculate the translation
  59409. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  59410. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  59411. //add it inverted to the delta
  59412. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  59413. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  59414. mesh.setPivotMatrix(oldPivot);
  59415. mesh.computeWorldMatrix(true);
  59416. }
  59417. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  59418. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  59419. this._tmpPosition.copyFrom(object.position);
  59420. }
  59421. impostor.setDeltaPosition(this._tmpDeltaPosition);
  59422. //Now update the impostor object
  59423. impostor.physicsBody.position.copy(this._tmpPosition);
  59424. impostor.physicsBody.quaternion.copy(quaternion);
  59425. };
  59426. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  59427. impostor.object.position.copyFrom(impostor.physicsBody.position);
  59428. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  59429. };
  59430. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  59431. impostor.physicsBody.position.copy(newPosition);
  59432. impostor.physicsBody.quaternion.copy(newRotation);
  59433. };
  59434. CannonJSPlugin.prototype.isSupported = function () {
  59435. return window.CANNON !== undefined;
  59436. };
  59437. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  59438. impostor.physicsBody.velocity.copy(velocity);
  59439. };
  59440. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  59441. impostor.physicsBody.angularVelocity.copy(velocity);
  59442. };
  59443. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  59444. var v = impostor.physicsBody.velocity;
  59445. if (!v)
  59446. return null;
  59447. return new BABYLON.Vector3(v.x, v.y, v.z);
  59448. };
  59449. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  59450. var v = impostor.physicsBody.angularVelocity;
  59451. if (!v)
  59452. return null;
  59453. return new BABYLON.Vector3(v.x, v.y, v.z);
  59454. };
  59455. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  59456. impostor.physicsBody.mass = mass;
  59457. impostor.physicsBody.updateMassProperties();
  59458. };
  59459. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  59460. return impostor.physicsBody.mass;
  59461. };
  59462. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  59463. return impostor.physicsBody.material.friction;
  59464. };
  59465. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  59466. impostor.physicsBody.material.friction = friction;
  59467. };
  59468. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  59469. return impostor.physicsBody.material.restitution;
  59470. };
  59471. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  59472. impostor.physicsBody.material.restitution = restitution;
  59473. };
  59474. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  59475. impostor.physicsBody.sleep();
  59476. };
  59477. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  59478. impostor.physicsBody.wakeUp();
  59479. };
  59480. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  59481. joint.physicsJoint.distance = maxDistance;
  59482. };
  59483. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  59484. if (!motorIndex) {
  59485. joint.physicsJoint.enableMotor();
  59486. }
  59487. };
  59488. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  59489. if (!motorIndex) {
  59490. joint.physicsJoint.disableMotor();
  59491. }
  59492. };
  59493. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  59494. if (!motorIndex) {
  59495. joint.physicsJoint.enableMotor();
  59496. joint.physicsJoint.setMotorSpeed(speed);
  59497. if (maxForce) {
  59498. this.setLimit(joint, maxForce);
  59499. }
  59500. }
  59501. };
  59502. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  59503. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  59504. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  59505. };
  59506. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  59507. var body = impostor.physicsBody;
  59508. mesh.position.x = body.position.x;
  59509. mesh.position.y = body.position.y;
  59510. mesh.position.z = body.position.z;
  59511. mesh.rotationQuaternion.x = body.quaternion.x;
  59512. mesh.rotationQuaternion.y = body.quaternion.y;
  59513. mesh.rotationQuaternion.z = body.quaternion.z;
  59514. mesh.rotationQuaternion.w = body.quaternion.w;
  59515. };
  59516. CannonJSPlugin.prototype.getRadius = function (impostor) {
  59517. var shape = impostor.physicsBody.shapes[0];
  59518. return shape.boundingSphereRadius;
  59519. };
  59520. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  59521. var shape = impostor.physicsBody.shapes[0];
  59522. result.x = shape.halfExtents.x * 2;
  59523. result.y = shape.halfExtents.y * 2;
  59524. result.z = shape.halfExtents.z * 2;
  59525. };
  59526. CannonJSPlugin.prototype.dispose = function () {
  59527. };
  59528. return CannonJSPlugin;
  59529. }());
  59530. BABYLON.CannonJSPlugin = CannonJSPlugin;
  59531. })(BABYLON || (BABYLON = {}));
  59532. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  59533. var BABYLON;
  59534. (function (BABYLON) {
  59535. var OimoJSPlugin = (function () {
  59536. function OimoJSPlugin(iterations) {
  59537. this.name = "OimoJSPlugin";
  59538. this._tmpImpostorsArray = [];
  59539. this._tmpPositionVector = BABYLON.Vector3.Zero();
  59540. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  59541. this.world.worldscale(1);
  59542. this.world.clear();
  59543. //making sure no stats are calculated
  59544. this.world.isNoStat = true;
  59545. }
  59546. OimoJSPlugin.prototype.setGravity = function (gravity) {
  59547. this.world.gravity.copy(gravity);
  59548. };
  59549. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  59550. this.world.timeStep = timeStep;
  59551. };
  59552. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  59553. var _this = this;
  59554. impostors.forEach(function (impostor) {
  59555. impostor.beforeStep();
  59556. });
  59557. this.world.step();
  59558. impostors.forEach(function (impostor) {
  59559. impostor.afterStep();
  59560. //update the ordered impostors array
  59561. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  59562. });
  59563. //check for collisions
  59564. var contact = this.world.contacts;
  59565. while (contact !== null) {
  59566. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  59567. contact = contact.next;
  59568. continue;
  59569. }
  59570. //is this body colliding with any other? get the impostor
  59571. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  59572. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  59573. if (!mainImpostor || !collidingImpostor) {
  59574. contact = contact.next;
  59575. continue;
  59576. }
  59577. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  59578. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  59579. contact = contact.next;
  59580. }
  59581. };
  59582. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  59583. var mass = impostor.physicsBody.massInfo.mass;
  59584. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  59585. };
  59586. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  59587. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  59588. this.applyImpulse(impostor, force, contactPoint);
  59589. };
  59590. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  59591. var _this = this;
  59592. //parent-child relationship. Does this impostor has a parent impostor?
  59593. if (impostor.parent) {
  59594. if (impostor.physicsBody) {
  59595. this.removePhysicsBody(impostor);
  59596. //TODO is that needed?
  59597. impostor.forceUpdate();
  59598. }
  59599. return;
  59600. }
  59601. if (impostor.isBodyInitRequired()) {
  59602. var bodyConfig = {
  59603. name: impostor.uniqueId,
  59604. //Oimo must have mass, also for static objects.
  59605. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  59606. size: [],
  59607. type: [],
  59608. pos: [],
  59609. rot: [],
  59610. move: impostor.getParam("mass") !== 0,
  59611. //Supporting older versions of Oimo
  59612. world: this.world
  59613. };
  59614. var impostors = [impostor];
  59615. var addToArray = function (parent) {
  59616. if (!parent.getChildMeshes)
  59617. return;
  59618. parent.getChildMeshes().forEach(function (m) {
  59619. if (m.physicsImpostor) {
  59620. impostors.push(m.physicsImpostor);
  59621. m.physicsImpostor._init();
  59622. }
  59623. });
  59624. };
  59625. addToArray(impostor.object);
  59626. var checkWithEpsilon_1 = function (value) {
  59627. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  59628. };
  59629. impostors.forEach(function (i) {
  59630. //get the correct bounding box
  59631. var oldQuaternion = i.object.rotationQuaternion;
  59632. var rot = new OIMO.Euler().setFromQuaternion({
  59633. x: impostor.object.rotationQuaternion.x,
  59634. y: impostor.object.rotationQuaternion.y,
  59635. z: impostor.object.rotationQuaternion.z,
  59636. s: impostor.object.rotationQuaternion.w
  59637. });
  59638. var extendSize = i.getObjectExtendSize();
  59639. if (i === impostor) {
  59640. var center = impostor.getObjectCenter();
  59641. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  59642. //Can also use Array.prototype.push.apply
  59643. bodyConfig.pos.push(center.x);
  59644. bodyConfig.pos.push(center.y);
  59645. bodyConfig.pos.push(center.z);
  59646. //tmp solution
  59647. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  59648. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  59649. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  59650. }
  59651. else {
  59652. bodyConfig.pos.push(i.object.position.x);
  59653. bodyConfig.pos.push(i.object.position.y);
  59654. bodyConfig.pos.push(i.object.position.z);
  59655. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  59656. bodyConfig.rot.push(0);
  59657. bodyConfig.rot.push(0);
  59658. bodyConfig.rot.push(0);
  59659. }
  59660. // register mesh
  59661. switch (i.type) {
  59662. case BABYLON.PhysicsImpostor.ParticleImpostor:
  59663. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  59664. case BABYLON.PhysicsImpostor.SphereImpostor:
  59665. var radiusX = extendSize.x;
  59666. var radiusY = extendSize.y;
  59667. var radiusZ = extendSize.z;
  59668. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  59669. bodyConfig.type.push('sphere');
  59670. //due to the way oimo works with compounds, add 3 times
  59671. bodyConfig.size.push(size);
  59672. bodyConfig.size.push(size);
  59673. bodyConfig.size.push(size);
  59674. break;
  59675. case BABYLON.PhysicsImpostor.CylinderImpostor:
  59676. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  59677. var sizeY = checkWithEpsilon_1(extendSize.y);
  59678. bodyConfig.type.push('cylinder');
  59679. bodyConfig.size.push(sizeX);
  59680. bodyConfig.size.push(sizeY);
  59681. //due to the way oimo works with compounds, add one more value.
  59682. bodyConfig.size.push(sizeY);
  59683. break;
  59684. case BABYLON.PhysicsImpostor.PlaneImpostor:
  59685. case BABYLON.PhysicsImpostor.BoxImpostor:
  59686. default:
  59687. var sizeX = checkWithEpsilon_1(extendSize.x);
  59688. var sizeY = checkWithEpsilon_1(extendSize.y);
  59689. var sizeZ = checkWithEpsilon_1(extendSize.z);
  59690. bodyConfig.type.push('box');
  59691. bodyConfig.size.push(sizeX);
  59692. bodyConfig.size.push(sizeY);
  59693. bodyConfig.size.push(sizeZ);
  59694. break;
  59695. }
  59696. //actually not needed, but hey...
  59697. i.object.rotationQuaternion = oldQuaternion;
  59698. });
  59699. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  59700. }
  59701. else {
  59702. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  59703. }
  59704. impostor.setDeltaPosition(this._tmpPositionVector);
  59705. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  59706. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  59707. };
  59708. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  59709. //impostor.physicsBody.dispose();
  59710. //Same as : (older oimo versions)
  59711. this.world.removeRigidBody(impostor.physicsBody);
  59712. };
  59713. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  59714. var mainBody = impostorJoint.mainImpostor.physicsBody;
  59715. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  59716. if (!mainBody || !connectedBody) {
  59717. return;
  59718. }
  59719. var jointData = impostorJoint.joint.jointData;
  59720. var options = jointData.nativeParams || {};
  59721. var type;
  59722. var nativeJointData = {
  59723. body1: mainBody,
  59724. body2: connectedBody,
  59725. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  59726. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  59727. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  59728. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  59729. min: options.min,
  59730. max: options.max,
  59731. collision: options.collision || jointData.collision,
  59732. spring: options.spring,
  59733. //supporting older version of Oimo
  59734. world: this.world
  59735. };
  59736. switch (impostorJoint.joint.type) {
  59737. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  59738. type = "jointBall";
  59739. break;
  59740. case BABYLON.PhysicsJoint.SpringJoint:
  59741. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  59742. var springData = jointData;
  59743. nativeJointData.min = springData.length || nativeJointData.min;
  59744. //Max should also be set, just make sure it is at least min
  59745. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  59746. case BABYLON.PhysicsJoint.DistanceJoint:
  59747. type = "jointDistance";
  59748. nativeJointData.max = jointData.maxDistance;
  59749. break;
  59750. case BABYLON.PhysicsJoint.PrismaticJoint:
  59751. type = "jointPrisme";
  59752. break;
  59753. case BABYLON.PhysicsJoint.SliderJoint:
  59754. type = "jointSlide";
  59755. break;
  59756. case BABYLON.PhysicsJoint.WheelJoint:
  59757. type = "jointWheel";
  59758. break;
  59759. case BABYLON.PhysicsJoint.HingeJoint:
  59760. default:
  59761. type = "jointHinge";
  59762. break;
  59763. }
  59764. nativeJointData.type = type;
  59765. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  59766. };
  59767. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  59768. //Bug in Oimo prevents us from disposing a joint in the playground
  59769. //joint.joint.physicsJoint.dispose();
  59770. //So we will bruteforce it!
  59771. try {
  59772. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  59773. }
  59774. catch (e) {
  59775. BABYLON.Tools.Warn(e);
  59776. }
  59777. };
  59778. OimoJSPlugin.prototype.isSupported = function () {
  59779. return OIMO !== undefined;
  59780. };
  59781. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  59782. if (!impostor.physicsBody.sleeping) {
  59783. //TODO check that
  59784. if (impostor.physicsBody.shapes.next) {
  59785. var parentShape = this._getLastShape(impostor.physicsBody);
  59786. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  59787. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  59788. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  59789. }
  59790. else {
  59791. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  59792. }
  59793. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  59794. impostor.object.rotationQuaternion.normalize();
  59795. }
  59796. };
  59797. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  59798. var body = impostor.physicsBody;
  59799. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  59800. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  59801. body.syncShapes();
  59802. body.awake();
  59803. };
  59804. OimoJSPlugin.prototype._getLastShape = function (body) {
  59805. var lastShape = body.shapes;
  59806. while (lastShape.next) {
  59807. lastShape = lastShape.next;
  59808. }
  59809. return lastShape;
  59810. };
  59811. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  59812. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  59813. };
  59814. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  59815. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  59816. };
  59817. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  59818. var v = impostor.physicsBody.linearVelocity;
  59819. if (!v)
  59820. return null;
  59821. return new BABYLON.Vector3(v.x, v.y, v.z);
  59822. };
  59823. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  59824. var v = impostor.physicsBody.angularVelocity;
  59825. if (!v)
  59826. return null;
  59827. return new BABYLON.Vector3(v.x, v.y, v.z);
  59828. };
  59829. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  59830. var staticBody = mass === 0;
  59831. //this will actually set the body's density and not its mass.
  59832. //But this is how oimo treats the mass variable.
  59833. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  59834. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  59835. };
  59836. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  59837. return impostor.physicsBody.shapes.density;
  59838. };
  59839. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  59840. return impostor.physicsBody.shapes.friction;
  59841. };
  59842. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  59843. impostor.physicsBody.shapes.friction = friction;
  59844. };
  59845. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  59846. return impostor.physicsBody.shapes.restitution;
  59847. };
  59848. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  59849. impostor.physicsBody.shapes.restitution = restitution;
  59850. };
  59851. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  59852. impostor.physicsBody.sleep();
  59853. };
  59854. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  59855. impostor.physicsBody.awake();
  59856. };
  59857. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  59858. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  59859. if (minDistance !== void 0) {
  59860. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  59861. }
  59862. };
  59863. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  59864. //TODO separate rotational and transational motors.
  59865. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  59866. if (motor) {
  59867. motor.setMotor(speed, maxForce);
  59868. }
  59869. };
  59870. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  59871. //TODO separate rotational and transational motors.
  59872. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  59873. if (motor) {
  59874. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  59875. }
  59876. };
  59877. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  59878. var body = impostor.physicsBody;
  59879. mesh.position.x = body.position.x;
  59880. mesh.position.y = body.position.y;
  59881. mesh.position.z = body.position.z;
  59882. mesh.rotationQuaternion.x = body.orientation.x;
  59883. mesh.rotationQuaternion.y = body.orientation.y;
  59884. mesh.rotationQuaternion.z = body.orientation.z;
  59885. mesh.rotationQuaternion.w = body.orientation.s;
  59886. };
  59887. OimoJSPlugin.prototype.getRadius = function (impostor) {
  59888. return impostor.physicsBody.shapes.radius;
  59889. };
  59890. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  59891. var shape = impostor.physicsBody.shapes;
  59892. result.x = shape.halfWidth * 2;
  59893. result.y = shape.halfHeight * 2;
  59894. result.z = shape.halfDepth * 2;
  59895. };
  59896. OimoJSPlugin.prototype.dispose = function () {
  59897. this.world.clear();
  59898. };
  59899. return OimoJSPlugin;
  59900. }());
  59901. BABYLON.OimoJSPlugin = OimoJSPlugin;
  59902. })(BABYLON || (BABYLON = {}));
  59903. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  59904. var BABYLON;
  59905. (function (BABYLON) {
  59906. var Internals;
  59907. (function (Internals) {
  59908. /*
  59909. * Based on jsTGALoader - Javascript loader for TGA file
  59910. * By Vincent Thibault
  59911. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  59912. */
  59913. var TGATools = (function () {
  59914. function TGATools() {
  59915. }
  59916. TGATools.GetTGAHeader = function (data) {
  59917. var offset = 0;
  59918. var header = {
  59919. id_length: data[offset++],
  59920. colormap_type: data[offset++],
  59921. image_type: data[offset++],
  59922. colormap_index: data[offset++] | data[offset++] << 8,
  59923. colormap_length: data[offset++] | data[offset++] << 8,
  59924. colormap_size: data[offset++],
  59925. origin: [
  59926. data[offset++] | data[offset++] << 8,
  59927. data[offset++] | data[offset++] << 8
  59928. ],
  59929. width: data[offset++] | data[offset++] << 8,
  59930. height: data[offset++] | data[offset++] << 8,
  59931. pixel_size: data[offset++],
  59932. flags: data[offset++]
  59933. };
  59934. return header;
  59935. };
  59936. TGATools.UploadContent = function (gl, data) {
  59937. // Not enough data to contain header ?
  59938. if (data.length < 19) {
  59939. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  59940. return;
  59941. }
  59942. // Read Header
  59943. var offset = 18;
  59944. var header = TGATools.GetTGAHeader(data);
  59945. // Assume it's a valid Targa file.
  59946. if (header.id_length + offset > data.length) {
  59947. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  59948. return;
  59949. }
  59950. // Skip not needed data
  59951. offset += header.id_length;
  59952. var use_rle = false;
  59953. var use_pal = false;
  59954. var use_rgb = false;
  59955. var use_grey = false;
  59956. // Get some informations.
  59957. switch (header.image_type) {
  59958. case TGATools._TYPE_RLE_INDEXED:
  59959. use_rle = true;
  59960. case TGATools._TYPE_INDEXED:
  59961. use_pal = true;
  59962. break;
  59963. case TGATools._TYPE_RLE_RGB:
  59964. use_rle = true;
  59965. case TGATools._TYPE_RGB:
  59966. use_rgb = true;
  59967. break;
  59968. case TGATools._TYPE_RLE_GREY:
  59969. use_rle = true;
  59970. case TGATools._TYPE_GREY:
  59971. use_grey = true;
  59972. break;
  59973. }
  59974. var pixel_data;
  59975. var numAlphaBits = header.flags & 0xf;
  59976. var pixel_size = header.pixel_size >> 3;
  59977. var pixel_total = header.width * header.height * pixel_size;
  59978. // Read palettes
  59979. var palettes;
  59980. if (use_pal) {
  59981. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  59982. }
  59983. // Read LRE
  59984. if (use_rle) {
  59985. pixel_data = new Uint8Array(pixel_total);
  59986. var c, count, i;
  59987. var localOffset = 0;
  59988. var pixels = new Uint8Array(pixel_size);
  59989. while (offset < pixel_total && localOffset < pixel_total) {
  59990. c = data[offset++];
  59991. count = (c & 0x7f) + 1;
  59992. // RLE pixels
  59993. if (c & 0x80) {
  59994. // Bind pixel tmp array
  59995. for (i = 0; i < pixel_size; ++i) {
  59996. pixels[i] = data[offset++];
  59997. }
  59998. // Copy pixel array
  59999. for (i = 0; i < count; ++i) {
  60000. pixel_data.set(pixels, localOffset + i * pixel_size);
  60001. }
  60002. localOffset += pixel_size * count;
  60003. }
  60004. else {
  60005. count *= pixel_size;
  60006. for (i = 0; i < count; ++i) {
  60007. pixel_data[localOffset + i] = data[offset++];
  60008. }
  60009. localOffset += count;
  60010. }
  60011. }
  60012. }
  60013. else {
  60014. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  60015. }
  60016. // Load to texture
  60017. var x_start, y_start, x_step, y_step, y_end, x_end;
  60018. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  60019. default:
  60020. case TGATools._ORIGIN_UL:
  60021. x_start = 0;
  60022. x_step = 1;
  60023. x_end = header.width;
  60024. y_start = 0;
  60025. y_step = 1;
  60026. y_end = header.height;
  60027. break;
  60028. case TGATools._ORIGIN_BL:
  60029. x_start = 0;
  60030. x_step = 1;
  60031. x_end = header.width;
  60032. y_start = header.height - 1;
  60033. y_step = -1;
  60034. y_end = -1;
  60035. break;
  60036. case TGATools._ORIGIN_UR:
  60037. x_start = header.width - 1;
  60038. x_step = -1;
  60039. x_end = -1;
  60040. y_start = 0;
  60041. y_step = 1;
  60042. y_end = header.height;
  60043. break;
  60044. case TGATools._ORIGIN_BR:
  60045. x_start = header.width - 1;
  60046. x_step = -1;
  60047. x_end = -1;
  60048. y_start = header.height - 1;
  60049. y_step = -1;
  60050. y_end = -1;
  60051. break;
  60052. }
  60053. // Load the specify method
  60054. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  60055. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  60056. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  60057. };
  60058. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60059. var image = pixel_data, colormap = palettes;
  60060. var width = header.width, height = header.height;
  60061. var color, i = 0, x, y;
  60062. var imageData = new Uint8Array(width * height * 4);
  60063. for (y = y_start; y !== y_end; y += y_step) {
  60064. for (x = x_start; x !== x_end; x += x_step, i++) {
  60065. color = image[i];
  60066. imageData[(x + width * y) * 4 + 3] = 255;
  60067. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  60068. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  60069. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  60070. }
  60071. }
  60072. return imageData;
  60073. };
  60074. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60075. var image = pixel_data;
  60076. var width = header.width, height = header.height;
  60077. var color, i = 0, x, y;
  60078. var imageData = new Uint8Array(width * height * 4);
  60079. for (y = y_start; y !== y_end; y += y_step) {
  60080. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60081. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  60082. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  60083. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  60084. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  60085. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  60086. }
  60087. }
  60088. return imageData;
  60089. };
  60090. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60091. var image = pixel_data;
  60092. var width = header.width, height = header.height;
  60093. var i = 0, x, y;
  60094. var imageData = new Uint8Array(width * height * 4);
  60095. for (y = y_start; y !== y_end; y += y_step) {
  60096. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  60097. imageData[(x + width * y) * 4 + 3] = 255;
  60098. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60099. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60100. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60101. }
  60102. }
  60103. return imageData;
  60104. };
  60105. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60106. var image = pixel_data;
  60107. var width = header.width, height = header.height;
  60108. var i = 0, x, y;
  60109. var imageData = new Uint8Array(width * height * 4);
  60110. for (y = y_start; y !== y_end; y += y_step) {
  60111. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  60112. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60113. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60114. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60115. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  60116. }
  60117. }
  60118. return imageData;
  60119. };
  60120. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60121. var image = pixel_data;
  60122. var width = header.width, height = header.height;
  60123. var color, i = 0, x, y;
  60124. var imageData = new Uint8Array(width * height * 4);
  60125. for (y = y_start; y !== y_end; y += y_step) {
  60126. for (x = x_start; x !== x_end; x += x_step, i++) {
  60127. color = image[i];
  60128. imageData[(x + width * y) * 4 + 0] = color;
  60129. imageData[(x + width * y) * 4 + 1] = color;
  60130. imageData[(x + width * y) * 4 + 2] = color;
  60131. imageData[(x + width * y) * 4 + 3] = 255;
  60132. }
  60133. }
  60134. return imageData;
  60135. };
  60136. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60137. var image = pixel_data;
  60138. var width = header.width, height = header.height;
  60139. var i = 0, x, y;
  60140. var imageData = new Uint8Array(width * height * 4);
  60141. for (y = y_start; y !== y_end; y += y_step) {
  60142. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60143. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  60144. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  60145. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60146. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  60147. }
  60148. }
  60149. return imageData;
  60150. };
  60151. return TGATools;
  60152. }());
  60153. TGATools._TYPE_NO_DATA = 0;
  60154. TGATools._TYPE_INDEXED = 1;
  60155. TGATools._TYPE_RGB = 2;
  60156. TGATools._TYPE_GREY = 3;
  60157. TGATools._TYPE_RLE_INDEXED = 9;
  60158. TGATools._TYPE_RLE_RGB = 10;
  60159. TGATools._TYPE_RLE_GREY = 11;
  60160. TGATools._ORIGIN_MASK = 0x30;
  60161. TGATools._ORIGIN_SHIFT = 0x04;
  60162. TGATools._ORIGIN_BL = 0x00;
  60163. TGATools._ORIGIN_BR = 0x01;
  60164. TGATools._ORIGIN_UL = 0x02;
  60165. TGATools._ORIGIN_UR = 0x03;
  60166. Internals.TGATools = TGATools;
  60167. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60168. })(BABYLON || (BABYLON = {}));
  60169. //# sourceMappingURL=babylon.tga.js.map
  60170. var BABYLON;
  60171. (function (BABYLON) {
  60172. var Internals;
  60173. (function (Internals) {
  60174. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  60175. // All values and structures referenced from:
  60176. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  60177. var DDS_MAGIC = 0x20534444;
  60178. 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;
  60179. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  60180. 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;
  60181. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  60182. function FourCCToInt32(value) {
  60183. return value.charCodeAt(0) +
  60184. (value.charCodeAt(1) << 8) +
  60185. (value.charCodeAt(2) << 16) +
  60186. (value.charCodeAt(3) << 24);
  60187. }
  60188. function Int32ToFourCC(value) {
  60189. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  60190. }
  60191. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  60192. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  60193. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  60194. var FOURCC_DX10 = FourCCToInt32("DX10");
  60195. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  60196. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  60197. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  60198. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  60199. var headerLengthInt = 31; // The header length in 32 bit ints
  60200. // Offsets into the header array
  60201. var off_magic = 0;
  60202. var off_size = 1;
  60203. var off_flags = 2;
  60204. var off_height = 3;
  60205. var off_width = 4;
  60206. var off_mipmapCount = 7;
  60207. var off_pfFlags = 20;
  60208. var off_pfFourCC = 21;
  60209. var off_RGBbpp = 22;
  60210. var off_RMask = 23;
  60211. var off_GMask = 24;
  60212. var off_BMask = 25;
  60213. var off_AMask = 26;
  60214. var off_caps1 = 27;
  60215. var off_caps2 = 28;
  60216. var off_caps3 = 29;
  60217. var off_caps4 = 30;
  60218. var off_dxgiFormat = 32;
  60219. ;
  60220. var DDSTools = (function () {
  60221. function DDSTools() {
  60222. }
  60223. DDSTools.GetDDSInfo = function (arrayBuffer) {
  60224. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  60225. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  60226. var mipmapCount = 1;
  60227. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  60228. mipmapCount = Math.max(1, header[off_mipmapCount]);
  60229. }
  60230. var fourCC = header[off_pfFourCC];
  60231. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  60232. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60233. switch (fourCC) {
  60234. case FOURCC_D3DFMT_R16G16B16A16F:
  60235. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60236. break;
  60237. case FOURCC_D3DFMT_R32G32B32A32F:
  60238. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60239. break;
  60240. case FOURCC_DX10:
  60241. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  60242. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60243. break;
  60244. }
  60245. }
  60246. return {
  60247. width: header[off_width],
  60248. height: header[off_height],
  60249. mipmapCount: mipmapCount,
  60250. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  60251. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  60252. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  60253. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  60254. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  60255. dxgiFormat: dxgiFormat,
  60256. textureType: textureType
  60257. };
  60258. };
  60259. DDSTools._ToHalfFloat = function (value) {
  60260. if (!DDSTools._FloatView) {
  60261. DDSTools._FloatView = new Float32Array(1);
  60262. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  60263. }
  60264. DDSTools._FloatView[0] = value;
  60265. var x = DDSTools._Int32View[0];
  60266. var bits = (x >> 16) & 0x8000; /* Get the sign */
  60267. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  60268. var e = (x >> 23) & 0xff; /* Using int is faster here */
  60269. /* If zero, or denormal, or exponent underflows too much for a denormal
  60270. * half, return signed zero. */
  60271. if (e < 103) {
  60272. return bits;
  60273. }
  60274. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  60275. if (e > 142) {
  60276. bits |= 0x7c00;
  60277. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  60278. * not Inf, so make sure we set one mantissa bit too. */
  60279. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  60280. return bits;
  60281. }
  60282. /* If exponent underflows but not too much, return a denormal */
  60283. if (e < 113) {
  60284. m |= 0x0800;
  60285. /* Extra rounding may overflow and set mantissa to 0 and exponent
  60286. * to 1, which is OK. */
  60287. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  60288. return bits;
  60289. }
  60290. bits |= ((e - 112) << 10) | (m >> 1);
  60291. bits += m & 1;
  60292. return bits;
  60293. };
  60294. DDSTools._FromHalfFloat = function (value) {
  60295. var s = (value & 0x8000) >> 15;
  60296. var e = (value & 0x7C00) >> 10;
  60297. var f = value & 0x03FF;
  60298. if (e === 0) {
  60299. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  60300. }
  60301. else if (e == 0x1F) {
  60302. return f ? NaN : ((s ? -1 : 1) * Infinity);
  60303. }
  60304. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  60305. };
  60306. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60307. var destArray = new Float32Array(dataLength);
  60308. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  60309. var index = 0;
  60310. for (var y = 0; y < height; y++) {
  60311. for (var x = 0; x < width; x++) {
  60312. var srcPos = (x + y * width) * 4;
  60313. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  60314. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  60315. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  60316. if (DDSTools.StoreLODInAlphaChannel) {
  60317. destArray[index + 3] = lod;
  60318. }
  60319. else {
  60320. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  60321. }
  60322. index += 4;
  60323. }
  60324. }
  60325. return destArray;
  60326. };
  60327. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60328. if (DDSTools.StoreLODInAlphaChannel) {
  60329. var destArray = new Uint16Array(dataLength);
  60330. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  60331. var index = 0;
  60332. for (var y = 0; y < height; y++) {
  60333. for (var x = 0; x < width; x++) {
  60334. var srcPos = (x + y * width) * 4;
  60335. destArray[index] = srcData[srcPos];
  60336. destArray[index + 1] = srcData[srcPos + 1];
  60337. destArray[index + 2] = srcData[srcPos + 2];
  60338. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  60339. index += 4;
  60340. }
  60341. }
  60342. return destArray;
  60343. }
  60344. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  60345. };
  60346. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60347. if (DDSTools.StoreLODInAlphaChannel) {
  60348. var destArray = new Float32Array(dataLength);
  60349. var srcData = new Float32Array(arrayBuffer, dataOffset);
  60350. var index = 0;
  60351. for (var y = 0; y < height; y++) {
  60352. for (var x = 0; x < width; x++) {
  60353. var srcPos = (x + y * width) * 4;
  60354. destArray[index] = srcData[srcPos];
  60355. destArray[index + 1] = srcData[srcPos + 1];
  60356. destArray[index + 2] = srcData[srcPos + 2];
  60357. destArray[index + 3] = lod;
  60358. index += 4;
  60359. }
  60360. }
  60361. return destArray;
  60362. }
  60363. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  60364. };
  60365. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60366. var destArray = new Uint8Array(dataLength);
  60367. var srcData = new Float32Array(arrayBuffer, dataOffset);
  60368. var index = 0;
  60369. for (var y = 0; y < height; y++) {
  60370. for (var x = 0; x < width; x++) {
  60371. var srcPos = (x + y * width) * 4;
  60372. destArray[index] = BABYLON.MathTools.Clamp(srcData[srcPos]) * 255;
  60373. destArray[index + 1] = BABYLON.MathTools.Clamp(srcData[srcPos + 1]) * 255;
  60374. destArray[index + 2] = BABYLON.MathTools.Clamp(srcData[srcPos + 2]) * 255;
  60375. if (DDSTools.StoreLODInAlphaChannel) {
  60376. destArray[index + 3] = lod;
  60377. }
  60378. else {
  60379. destArray[index + 3] = BABYLON.MathTools.Clamp(srcData[srcPos + 3]) * 255;
  60380. }
  60381. index += 4;
  60382. }
  60383. }
  60384. return destArray;
  60385. };
  60386. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60387. var destArray = new Uint8Array(dataLength);
  60388. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  60389. var index = 0;
  60390. for (var y = 0; y < height; y++) {
  60391. for (var x = 0; x < width; x++) {
  60392. var srcPos = (x + y * width) * 4;
  60393. destArray[index] = BABYLON.MathTools.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  60394. destArray[index + 1] = BABYLON.MathTools.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  60395. destArray[index + 2] = BABYLON.MathTools.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  60396. if (DDSTools.StoreLODInAlphaChannel) {
  60397. destArray[index + 3] = lod;
  60398. }
  60399. else {
  60400. destArray[index + 3] = BABYLON.MathTools.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  60401. }
  60402. index += 4;
  60403. }
  60404. }
  60405. return destArray;
  60406. };
  60407. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60408. var byteArray = new Uint8Array(dataLength);
  60409. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  60410. var index = 0;
  60411. for (var y = 0; y < height; y++) {
  60412. for (var x = 0; x < width; x++) {
  60413. var srcPos = (x + y * width) * 4;
  60414. byteArray[index] = srcData[srcPos + 2];
  60415. byteArray[index + 1] = srcData[srcPos + 1];
  60416. byteArray[index + 2] = srcData[srcPos];
  60417. byteArray[index + 3] = srcData[srcPos + 3];
  60418. index += 4;
  60419. }
  60420. }
  60421. return byteArray;
  60422. };
  60423. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60424. var byteArray = new Uint8Array(dataLength);
  60425. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  60426. var index = 0;
  60427. for (var y = 0; y < height; y++) {
  60428. for (var x = 0; x < width; x++) {
  60429. var srcPos = (x + y * width) * 3;
  60430. byteArray[index] = srcData[srcPos + 2];
  60431. byteArray[index + 1] = srcData[srcPos + 1];
  60432. byteArray[index + 2] = srcData[srcPos];
  60433. index += 3;
  60434. }
  60435. }
  60436. return byteArray;
  60437. };
  60438. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60439. var byteArray = new Uint8Array(dataLength);
  60440. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  60441. var index = 0;
  60442. for (var y = 0; y < height; y++) {
  60443. for (var x = 0; x < width; x++) {
  60444. var srcPos = (x + y * width);
  60445. byteArray[index] = srcData[srcPos];
  60446. index++;
  60447. }
  60448. }
  60449. return byteArray;
  60450. };
  60451. DDSTools.UploadDDSLevels = function (engine, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  60452. if (lodIndex === void 0) { lodIndex = -1; }
  60453. var gl = engine._gl;
  60454. var ext = engine.getCaps().s3tc;
  60455. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  60456. if (header[off_magic] != DDS_MAGIC) {
  60457. BABYLON.Tools.Error("Invalid magic number in DDS header");
  60458. return;
  60459. }
  60460. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  60461. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  60462. return;
  60463. }
  60464. if (info.isCompressed && !ext) {
  60465. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  60466. return;
  60467. }
  60468. var bpp = header[off_RGBbpp];
  60469. dataOffset = header[off_size] + 4;
  60470. var computeFormats = false;
  60471. if (info.isFourCC) {
  60472. fourCC = header[off_pfFourCC];
  60473. switch (fourCC) {
  60474. case FOURCC_DXT1:
  60475. blockBytes = 8;
  60476. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  60477. break;
  60478. case FOURCC_DXT3:
  60479. blockBytes = 16;
  60480. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  60481. break;
  60482. case FOURCC_DXT5:
  60483. blockBytes = 16;
  60484. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  60485. break;
  60486. case FOURCC_D3DFMT_R16G16B16A16F:
  60487. computeFormats = true;
  60488. break;
  60489. case FOURCC_D3DFMT_R32G32B32A32F:
  60490. computeFormats = true;
  60491. break;
  60492. case FOURCC_DX10:
  60493. // There is an additionnal header so dataOffset need to be changed
  60494. dataOffset += 5 * 4; // 5 uints
  60495. var supported = false;
  60496. switch (info.dxgiFormat) {
  60497. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  60498. computeFormats = true;
  60499. supported = true;
  60500. break;
  60501. case DXGI_FORMAT_B8G8R8X8_UNORM:
  60502. info.isRGB = true;
  60503. info.isFourCC = false;
  60504. bpp = 32;
  60505. supported = true;
  60506. break;
  60507. }
  60508. if (supported) {
  60509. break;
  60510. }
  60511. default:
  60512. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  60513. return;
  60514. }
  60515. }
  60516. if (computeFormats) {
  60517. format = engine._getWebGLTextureType(info.textureType);
  60518. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  60519. }
  60520. mipmapCount = 1;
  60521. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  60522. mipmapCount = Math.max(1, header[off_mipmapCount]);
  60523. }
  60524. for (var face = 0; face < faces; face++) {
  60525. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  60526. width = header[off_width];
  60527. height = header[off_height];
  60528. for (mip = 0; mip < mipmapCount; ++mip) {
  60529. if (lodIndex === -1 || lodIndex === mip) {
  60530. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  60531. var i = (lodIndex === -1) ? mip : 0;
  60532. if (!info.isCompressed && info.isFourCC) {
  60533. dataLength = width * height * 4;
  60534. var floatArray;
  60535. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  60536. if (bpp === 128) {
  60537. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60538. }
  60539. else if (bpp === 64) {
  60540. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60541. }
  60542. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60543. format = engine._getWebGLTextureType(info.textureType);
  60544. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  60545. }
  60546. else {
  60547. if (bpp === 128) {
  60548. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60549. }
  60550. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  60551. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60552. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60553. format = engine._getWebGLTextureType(info.textureType);
  60554. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  60555. }
  60556. else {
  60557. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  60558. }
  60559. }
  60560. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  60561. }
  60562. else if (info.isRGB) {
  60563. if (bpp === 24) {
  60564. dataLength = width * height * 3;
  60565. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60566. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  60567. }
  60568. else {
  60569. dataLength = width * height * 4;
  60570. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60571. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  60572. }
  60573. }
  60574. else if (info.isLuminance) {
  60575. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  60576. var unpaddedRowSize = width;
  60577. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  60578. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  60579. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60580. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  60581. }
  60582. else {
  60583. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  60584. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  60585. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  60586. }
  60587. }
  60588. dataOffset += width * height * (bpp / 8);
  60589. width *= 0.5;
  60590. height *= 0.5;
  60591. width = Math.max(1.0, width);
  60592. height = Math.max(1.0, height);
  60593. }
  60594. }
  60595. };
  60596. return DDSTools;
  60597. }());
  60598. DDSTools.StoreLODInAlphaChannel = false;
  60599. Internals.DDSTools = DDSTools;
  60600. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60601. })(BABYLON || (BABYLON = {}));
  60602. //# sourceMappingURL=babylon.dds.js.map
  60603. var BABYLON;
  60604. (function (BABYLON) {
  60605. var Internals;
  60606. (function (Internals) {
  60607. /**
  60608. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  60609. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  60610. */
  60611. var KhronosTextureContainer = (function () {
  60612. /**
  60613. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  60614. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  60615. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  60616. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  60617. */
  60618. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  60619. this.arrayBuffer = arrayBuffer;
  60620. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  60621. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  60622. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  60623. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  60624. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  60625. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  60626. BABYLON.Tools.Error("texture missing KTX identifier");
  60627. return;
  60628. }
  60629. // load the reset of the header in native 32 bit int
  60630. var header = new Int32Array(this.arrayBuffer, 12, 13);
  60631. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  60632. var oppositeEndianess = header[0] === 0x01020304;
  60633. // read all the header elements in order they exist in the file, without modification (sans endainness)
  60634. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  60635. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  60636. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  60637. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  60638. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  60639. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  60640. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  60641. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  60642. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  60643. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  60644. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  60645. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  60646. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  60647. if (this.glType !== 0) {
  60648. BABYLON.Tools.Error("only compressed formats currently supported");
  60649. return;
  60650. }
  60651. else {
  60652. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  60653. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  60654. }
  60655. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  60656. BABYLON.Tools.Error("only 2D textures currently supported");
  60657. return;
  60658. }
  60659. if (this.numberOfArrayElements !== 0) {
  60660. BABYLON.Tools.Error("texture arrays not currently supported");
  60661. return;
  60662. }
  60663. if (this.numberOfFaces !== facesExpected) {
  60664. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  60665. return;
  60666. }
  60667. // we now have a completely validated file, so could use existence of loadType as success
  60668. // would need to make this more elaborate & adjust checks above to support more than one load type
  60669. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  60670. }
  60671. // not as fast hardware based, but will probably never need to use
  60672. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  60673. return ((val & 0xFF) << 24)
  60674. | ((val & 0xFF00) << 8)
  60675. | ((val >> 8) & 0xFF00)
  60676. | ((val >> 24) & 0xFF);
  60677. };
  60678. /**
  60679. * It is assumed that the texture has already been created & is currently bound
  60680. */
  60681. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  60682. switch (this.loadType) {
  60683. case KhronosTextureContainer.COMPRESSED_2D:
  60684. this._upload2DCompressedLevels(gl, loadMipmaps);
  60685. break;
  60686. case KhronosTextureContainer.TEX_2D:
  60687. case KhronosTextureContainer.COMPRESSED_3D:
  60688. case KhronosTextureContainer.TEX_3D:
  60689. }
  60690. };
  60691. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  60692. // initialize width & height for level 1
  60693. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  60694. var width = this.pixelWidth;
  60695. var height = this.pixelHeight;
  60696. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  60697. for (var level = 0; level < mipmapCount; level++) {
  60698. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  60699. for (var face = 0; face < this.numberOfFaces; face++) {
  60700. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  60701. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  60702. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  60703. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  60704. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  60705. }
  60706. width = Math.max(1.0, width * 0.5);
  60707. height = Math.max(1.0, height * 0.5);
  60708. }
  60709. };
  60710. return KhronosTextureContainer;
  60711. }());
  60712. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  60713. // load types
  60714. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  60715. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  60716. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  60717. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  60718. Internals.KhronosTextureContainer = KhronosTextureContainer;
  60719. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60720. })(BABYLON || (BABYLON = {}));
  60721. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  60722. var BABYLON;
  60723. (function (BABYLON) {
  60724. var DynamicFloatArrayElementInfo = (function () {
  60725. function DynamicFloatArrayElementInfo() {
  60726. }
  60727. return DynamicFloatArrayElementInfo;
  60728. }());
  60729. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  60730. /**
  60731. * 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.
  60732. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  60733. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  60734. * 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.
  60735. * 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.
  60736. * 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".
  60737. */
  60738. var DynamicFloatArray = (function () {
  60739. /**
  60740. * Construct an instance of the dynamic float array
  60741. * @param stride size of one element in float (i.e. not bytes!)
  60742. * @param initialElementCount the number of available entries at construction
  60743. */
  60744. function DynamicFloatArray(stride, initialElementCount) {
  60745. this.compareValueOffset = null;
  60746. this.sortingAscending = true;
  60747. this._stride = stride;
  60748. this.buffer = new Float32Array(stride * initialElementCount);
  60749. this._lastUsed = 0;
  60750. this._firstFree = 0;
  60751. this._allEntries = new Array(initialElementCount);
  60752. this._freeEntries = new Array(initialElementCount);
  60753. for (var i = 0; i < initialElementCount; i++) {
  60754. var element = new DynamicFloatArrayElementInfo();
  60755. element.offset = i * stride;
  60756. this._allEntries[i] = element;
  60757. this._freeEntries[initialElementCount - i - 1] = element;
  60758. }
  60759. }
  60760. /**
  60761. * Allocate an element in the array.
  60762. * @return the element info instance that contains the offset into the main buffer of the element's location.
  60763. * Beware, this offset may change when you call pack()
  60764. */
  60765. DynamicFloatArray.prototype.allocElement = function () {
  60766. if (this._freeEntries.length === 0) {
  60767. this._growBuffer();
  60768. }
  60769. var el = this._freeEntries.pop();
  60770. this._lastUsed = Math.max(el.offset, this._lastUsed);
  60771. if (el.offset === this._firstFree) {
  60772. if (this._freeEntries.length > 0) {
  60773. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  60774. }
  60775. else {
  60776. this._firstFree += this._stride;
  60777. }
  60778. }
  60779. return el;
  60780. };
  60781. /**
  60782. * Free the element corresponding to the given element info
  60783. * @param elInfo the element that describe the allocated element
  60784. */
  60785. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  60786. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  60787. this._freeEntries.push(elInfo);
  60788. };
  60789. /**
  60790. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  60791. * 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().
  60792. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  60793. */
  60794. DynamicFloatArray.prototype.pack = function () {
  60795. // no free slot? no need to pack
  60796. if (this._freeEntries.length === 0) {
  60797. return this.buffer;
  60798. }
  60799. // If the buffer is already packed the last used will always be lower than the first free
  60800. // 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.
  60801. if (this._lastUsed < this._firstFree) {
  60802. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  60803. return elementsBuffer_1;
  60804. }
  60805. var s = this._stride;
  60806. // 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
  60807. var lastFree = new DynamicFloatArrayElementInfo();
  60808. lastFree.offset = this.totalElementCount * s;
  60809. this._freeEntries.push(lastFree);
  60810. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  60811. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  60812. var firstFreeSlotOffset = sortedFree[0].offset;
  60813. var freeZoneSize = 1;
  60814. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  60815. var prevOffset = sortedFree[0].offset;
  60816. for (var i = 1; i < sortedFree.length; i++) {
  60817. // 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
  60818. if (firstFreeSlotOffset >= occupiedZoneSize) {
  60819. break;
  60820. }
  60821. var curFree = sortedFree[i];
  60822. var curOffset = curFree.offset;
  60823. // Compute the distance between this offset and the previous
  60824. var distance = curOffset - prevOffset;
  60825. // If the distance is the stride size, they are adjacent, it good, move to the next
  60826. if (distance === s) {
  60827. // Free zone is one element bigger
  60828. ++freeZoneSize;
  60829. // as we're about to iterate to the next, the cur becomes the previous...
  60830. prevOffset = curOffset;
  60831. continue;
  60832. }
  60833. // Distance is bigger, which means there's x element between the previous free and this one
  60834. var usedRange = (distance / s) - 1;
  60835. // Two cases the free zone is smaller than the data to move or bigger
  60836. // Copy what can fit in the free zone
  60837. var curMoveOffset = curOffset - s;
  60838. var copyCount = Math.min(freeZoneSize, usedRange);
  60839. for (var j = 0; j < copyCount; j++) {
  60840. var freeI = firstFreeSlotOffset / s;
  60841. var curI = curMoveOffset / s;
  60842. var moveEl = sortedAll[curI];
  60843. this._moveElement(moveEl, firstFreeSlotOffset);
  60844. var replacedEl = sortedAll[freeI];
  60845. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  60846. replacedEl.offset = curMoveOffset;
  60847. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  60848. sortedAll[freeI] = moveEl;
  60849. sortedAll[curI] = replacedEl;
  60850. curMoveOffset -= s;
  60851. firstFreeSlotOffset += s;
  60852. }
  60853. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  60854. if (freeZoneSize <= usedRange) {
  60855. firstFreeSlotOffset = curMoveOffset + s;
  60856. freeZoneSize = 1 + copyCount;
  60857. }
  60858. else {
  60859. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  60860. }
  60861. // as we're about to iterate to the next, the cur becomes the previous...
  60862. prevOffset = curOffset;
  60863. }
  60864. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  60865. this._lastUsed = firstFreeSlotOffset - s;
  60866. this._firstFree = firstFreeSlotOffset;
  60867. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  60868. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  60869. this._allEntries = sortedAll;
  60870. return elementsBuffer;
  60871. };
  60872. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  60873. for (var i = 0; i < this._stride; i++) {
  60874. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  60875. }
  60876. element.offset = destOffset;
  60877. };
  60878. DynamicFloatArray.prototype._growBuffer = function () {
  60879. // Allocate the new buffer with 50% more entries, copy the content of the current one
  60880. var newElCount = Math.floor(this.totalElementCount * 1.5);
  60881. var newBuffer = new Float32Array(newElCount * this._stride);
  60882. newBuffer.set(this.buffer);
  60883. var curCount = this.totalElementCount;
  60884. var addedCount = newElCount - this.totalElementCount;
  60885. for (var i = 0; i < addedCount; i++) {
  60886. var element = new DynamicFloatArrayElementInfo();
  60887. element.offset = (curCount + i) * this.stride;
  60888. this._allEntries.push(element);
  60889. this._freeEntries[addedCount - i - 1] = element;
  60890. }
  60891. this._firstFree = curCount * this.stride;
  60892. this.buffer = newBuffer;
  60893. };
  60894. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  60895. /**
  60896. * Get the total count of entries that can fit in the current buffer
  60897. * @returns the elements count
  60898. */
  60899. get: function () {
  60900. return this._allEntries.length;
  60901. },
  60902. enumerable: true,
  60903. configurable: true
  60904. });
  60905. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  60906. /**
  60907. * Get the count of free entries that can still be allocated without resizing the buffer
  60908. * @returns the free elements count
  60909. */
  60910. get: function () {
  60911. return this._freeEntries.length;
  60912. },
  60913. enumerable: true,
  60914. configurable: true
  60915. });
  60916. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  60917. /**
  60918. * Get the count of allocated elements
  60919. * @returns the allocated elements count
  60920. */
  60921. get: function () {
  60922. return this._allEntries.length - this._freeEntries.length;
  60923. },
  60924. enumerable: true,
  60925. configurable: true
  60926. });
  60927. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  60928. /**
  60929. * Return the size of one element in float
  60930. * @returns the size in float
  60931. */
  60932. get: function () {
  60933. return this._stride;
  60934. },
  60935. enumerable: true,
  60936. configurable: true
  60937. });
  60938. DynamicFloatArray.prototype.sort = function () {
  60939. var _this = this;
  60940. if (!this.compareValueOffset) {
  60941. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  60942. }
  60943. var count = this.usedElementCount;
  60944. // Do we have to (re)create the sort table?
  60945. if (!this._sortTable || this._sortTable.length < count) {
  60946. // 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...
  60947. var newCount = Math.min(this.totalElementCount, count * 2);
  60948. this._sortTable = new Array(newCount);
  60949. }
  60950. if (!this._sortedTable || this._sortedTable.length !== count) {
  60951. this._sortedTable = new Array(count);
  60952. }
  60953. // Because, you know...
  60954. this.pack();
  60955. //let stride = this.stride;
  60956. //for (let i = 0; i < count; i++) {
  60957. // let si = this._sortTable[i];
  60958. // if (!si) {
  60959. // si = new SortInfo();
  60960. // this._sortTable[i] = si;
  60961. // }
  60962. // si.entry = this._allEntries[i];
  60963. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  60964. // si.swapedOffset = null;
  60965. // this._sortedTable[i] = si;
  60966. //}
  60967. var curOffset = 0;
  60968. var stride = this.stride;
  60969. for (var i = 0; i < count; i++, curOffset += stride) {
  60970. var si = this._sortTable[i];
  60971. if (!si) {
  60972. si = new SortInfo();
  60973. this._sortTable[i] = si;
  60974. }
  60975. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  60976. si.offset = curOffset;
  60977. si.swapedOffset = null;
  60978. this._sortedTable[i] = si;
  60979. }
  60980. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  60981. if (this.sortingAscending) {
  60982. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  60983. }
  60984. else {
  60985. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  60986. }
  60987. var swapElements = function (src, dst) {
  60988. for (var i = 0; i < stride; i++) {
  60989. var tps = _this.buffer[dst + i];
  60990. _this.buffer[dst + i] = _this.buffer[src + i];
  60991. _this.buffer[src + i] = tps;
  60992. }
  60993. };
  60994. // 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:
  60995. // 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),
  60996. // and I still want something with a good algorithm complexity.
  60997. // 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,
  60998. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  60999. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  61000. // 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
  61001. // until we find a SortInfo object without a swapedOffset which means we got the right location
  61002. // 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
  61003. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  61004. for (var i = 0; i < count; i++) {
  61005. // Get the element to move
  61006. var sourceSI = this._sortedTable[i];
  61007. var destSI = this._sortTable[i];
  61008. var sourceOff = sourceSI.offset;
  61009. // If the source changed location, find the new one
  61010. if (sourceSI.swapedOffset) {
  61011. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  61012. var curSI = sourceSI;
  61013. while (curSI.swapedOffset) {
  61014. curSI = this._sortTable[curSI.swapedOffset / stride];
  61015. }
  61016. // Finally get the right location
  61017. sourceOff = curSI.offset;
  61018. }
  61019. // Tag the element being replaced with its new location
  61020. destSI.swapedOffset = sourceOff;
  61021. // Swap elements (only if needed)
  61022. if (sourceOff !== destSI.offset) {
  61023. swapElements(sourceOff, destSI.offset);
  61024. }
  61025. // Update the offset in the corresponding DFAE
  61026. //sourceSI.entry.offset = destSI.entry.offset;
  61027. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  61028. }
  61029. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61030. return true;
  61031. };
  61032. return DynamicFloatArray;
  61033. }());
  61034. BABYLON.DynamicFloatArray = DynamicFloatArray;
  61035. var SortInfo = (function () {
  61036. function SortInfo() {
  61037. this.compareData = this.offset = this.swapedOffset = null;
  61038. }
  61039. return SortInfo;
  61040. }());
  61041. })(BABYLON || (BABYLON = {}));
  61042. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  61043. var BABYLON;
  61044. (function (BABYLON) {
  61045. var Debug;
  61046. (function (Debug) {
  61047. /**
  61048. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  61049. */
  61050. var SkeletonViewer = (function () {
  61051. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  61052. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  61053. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  61054. this.skeleton = skeleton;
  61055. this.mesh = mesh;
  61056. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  61057. this.renderingGroupId = renderingGroupId;
  61058. this.color = BABYLON.Color3.White();
  61059. this._debugLines = [];
  61060. this._isEnabled = false;
  61061. this._scene = scene;
  61062. this.update();
  61063. this._renderFunction = this.update.bind(this);
  61064. }
  61065. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  61066. get: function () {
  61067. return this._isEnabled;
  61068. },
  61069. set: function (value) {
  61070. if (this._isEnabled === value) {
  61071. return;
  61072. }
  61073. this._isEnabled = value;
  61074. if (value) {
  61075. this._scene.registerBeforeRender(this._renderFunction);
  61076. }
  61077. else {
  61078. this._scene.unregisterBeforeRender(this._renderFunction);
  61079. }
  61080. },
  61081. enumerable: true,
  61082. configurable: true
  61083. });
  61084. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  61085. if (x === void 0) { x = 0; }
  61086. if (y === void 0) { y = 0; }
  61087. if (z === void 0) { z = 0; }
  61088. var tmat = BABYLON.Tmp.Matrix[0];
  61089. var parentBone = bone.getParent();
  61090. tmat.copyFrom(bone.getLocalMatrix());
  61091. if (x !== 0 || y !== 0 || z !== 0) {
  61092. var tmat2 = BABYLON.Tmp.Matrix[1];
  61093. BABYLON.Matrix.IdentityToRef(tmat2);
  61094. tmat2.m[12] = x;
  61095. tmat2.m[13] = y;
  61096. tmat2.m[14] = z;
  61097. tmat2.multiplyToRef(tmat, tmat);
  61098. }
  61099. if (parentBone) {
  61100. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  61101. }
  61102. tmat.multiplyToRef(meshMat, tmat);
  61103. position.x = tmat.m[12];
  61104. position.y = tmat.m[13];
  61105. position.z = tmat.m[14];
  61106. };
  61107. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  61108. var len = bones.length;
  61109. var meshPos = this.mesh.position;
  61110. for (var i = 0; i < len; i++) {
  61111. var bone = bones[i];
  61112. var points = this._debugLines[i];
  61113. if (!points) {
  61114. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61115. this._debugLines[i] = points;
  61116. }
  61117. this._getBonePosition(points[0], bone, meshMat);
  61118. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  61119. points[0].subtractInPlace(meshPos);
  61120. points[1].subtractInPlace(meshPos);
  61121. }
  61122. };
  61123. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  61124. var len = bones.length;
  61125. var boneNum = 0;
  61126. var meshPos = this.mesh.position;
  61127. for (var i = len - 1; i >= 0; i--) {
  61128. var childBone = bones[i];
  61129. var parentBone = childBone.getParent();
  61130. if (!parentBone) {
  61131. continue;
  61132. }
  61133. var points = this._debugLines[boneNum];
  61134. if (!points) {
  61135. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61136. this._debugLines[boneNum] = points;
  61137. }
  61138. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  61139. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  61140. points[0].subtractInPlace(meshPos);
  61141. points[1].subtractInPlace(meshPos);
  61142. boneNum++;
  61143. }
  61144. };
  61145. SkeletonViewer.prototype.update = function () {
  61146. if (this.autoUpdateBonesMatrices) {
  61147. this.skeleton.computeAbsoluteTransforms();
  61148. }
  61149. if (this.skeleton.bones[0].length === undefined) {
  61150. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61151. }
  61152. else {
  61153. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61154. }
  61155. if (!this._debugMesh) {
  61156. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  61157. this._debugMesh.renderingGroupId = this.renderingGroupId;
  61158. }
  61159. else {
  61160. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  61161. }
  61162. this._debugMesh.position.copyFrom(this.mesh.position);
  61163. this._debugMesh.color = this.color;
  61164. };
  61165. SkeletonViewer.prototype.dispose = function () {
  61166. if (this._debugMesh) {
  61167. this.isEnabled = false;
  61168. this._debugMesh.dispose();
  61169. this._debugMesh = null;
  61170. }
  61171. };
  61172. return SkeletonViewer;
  61173. }());
  61174. Debug.SkeletonViewer = SkeletonViewer;
  61175. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61176. })(BABYLON || (BABYLON = {}));
  61177. //# sourceMappingURL=babylon.skeletonViewer.js.map
  61178. var BABYLON;
  61179. (function (BABYLON) {
  61180. var Debug;
  61181. (function (Debug) {
  61182. var AxesViewer = (function () {
  61183. function AxesViewer(scene, scaleLines) {
  61184. if (scaleLines === void 0) { scaleLines = 1; }
  61185. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61186. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61187. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61188. this.scaleLines = 1;
  61189. this.scaleLines = scaleLines;
  61190. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  61191. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  61192. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  61193. this._xmesh.renderingGroupId = 2;
  61194. this._ymesh.renderingGroupId = 2;
  61195. this._zmesh.renderingGroupId = 2;
  61196. this._xmesh.material.checkReadyOnlyOnce = true;
  61197. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  61198. this._ymesh.material.checkReadyOnlyOnce = true;
  61199. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  61200. this._zmesh.material.checkReadyOnlyOnce = true;
  61201. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  61202. this.scene = scene;
  61203. }
  61204. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  61205. var scaleLines = this.scaleLines;
  61206. this._xmesh.position.copyFrom(position);
  61207. this._ymesh.position.copyFrom(position);
  61208. this._zmesh.position.copyFrom(position);
  61209. var point2 = this._xline[1];
  61210. point2.x = xaxis.x * scaleLines;
  61211. point2.y = xaxis.y * scaleLines;
  61212. point2.z = xaxis.z * scaleLines;
  61213. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  61214. point2 = this._yline[1];
  61215. point2.x = yaxis.x * scaleLines;
  61216. point2.y = yaxis.y * scaleLines;
  61217. point2.z = yaxis.z * scaleLines;
  61218. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  61219. point2 = this._zline[1];
  61220. point2.x = zaxis.x * scaleLines;
  61221. point2.y = zaxis.y * scaleLines;
  61222. point2.z = zaxis.z * scaleLines;
  61223. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  61224. };
  61225. AxesViewer.prototype.dispose = function () {
  61226. if (this._xmesh) {
  61227. this._xmesh.dispose();
  61228. this._ymesh.dispose();
  61229. this._zmesh.dispose();
  61230. this._xmesh = null;
  61231. this._ymesh = null;
  61232. this._zmesh = null;
  61233. this._xline = null;
  61234. this._yline = null;
  61235. this._zline = null;
  61236. this.scene = null;
  61237. }
  61238. };
  61239. return AxesViewer;
  61240. }());
  61241. Debug.AxesViewer = AxesViewer;
  61242. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61243. })(BABYLON || (BABYLON = {}));
  61244. //# sourceMappingURL=babylon.axesViewer.js.map
  61245. var BABYLON;
  61246. (function (BABYLON) {
  61247. var Debug;
  61248. (function (Debug) {
  61249. var BoneAxesViewer = (function (_super) {
  61250. __extends(BoneAxesViewer, _super);
  61251. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  61252. if (scaleLines === void 0) { scaleLines = 1; }
  61253. var _this = _super.call(this, scene, scaleLines) || this;
  61254. _this.pos = BABYLON.Vector3.Zero();
  61255. _this.xaxis = BABYLON.Vector3.Zero();
  61256. _this.yaxis = BABYLON.Vector3.Zero();
  61257. _this.zaxis = BABYLON.Vector3.Zero();
  61258. _this.mesh = mesh;
  61259. _this.bone = bone;
  61260. return _this;
  61261. }
  61262. BoneAxesViewer.prototype.update = function () {
  61263. var bone = this.bone;
  61264. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  61265. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  61266. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  61267. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  61268. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  61269. };
  61270. BoneAxesViewer.prototype.dispose = function () {
  61271. if (this.pos) {
  61272. this.pos = null;
  61273. this.xaxis = null;
  61274. this.yaxis = null;
  61275. this.zaxis = null;
  61276. this.mesh = null;
  61277. this.bone = null;
  61278. _super.prototype.dispose.call(this);
  61279. }
  61280. };
  61281. return BoneAxesViewer;
  61282. }(Debug.AxesViewer));
  61283. Debug.BoneAxesViewer = BoneAxesViewer;
  61284. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61285. })(BABYLON || (BABYLON = {}));
  61286. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  61287. var BABYLON;
  61288. (function (BABYLON) {
  61289. var RayHelper = (function () {
  61290. function RayHelper(ray) {
  61291. this.ray = ray;
  61292. }
  61293. RayHelper.CreateAndShow = function (ray, scene, color) {
  61294. var helper = new RayHelper(ray);
  61295. helper.show(scene, color);
  61296. return helper;
  61297. };
  61298. RayHelper.prototype.show = function (scene, color) {
  61299. if (!this._renderFunction) {
  61300. var ray = this.ray;
  61301. this._renderFunction = this._render.bind(this);
  61302. this._scene = scene;
  61303. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  61304. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  61305. this._scene.registerBeforeRender(this._renderFunction);
  61306. }
  61307. if (color) {
  61308. this._renderLine.color.copyFrom(color);
  61309. }
  61310. };
  61311. RayHelper.prototype.hide = function () {
  61312. if (this._renderFunction) {
  61313. this._scene.unregisterBeforeRender(this._renderFunction);
  61314. this._scene = null;
  61315. this._renderFunction = null;
  61316. this._renderLine.dispose();
  61317. this._renderLine = null;
  61318. this._renderPoints = null;
  61319. }
  61320. };
  61321. RayHelper.prototype._render = function () {
  61322. var ray = this.ray;
  61323. var point = this._renderPoints[1];
  61324. var len = Math.min(ray.length, 1000000);
  61325. point.copyFrom(ray.direction);
  61326. point.scaleInPlace(len);
  61327. point.addInPlace(ray.origin);
  61328. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  61329. };
  61330. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  61331. this._attachedToMesh = mesh;
  61332. var ray = this.ray;
  61333. if (!ray.direction) {
  61334. ray.direction = BABYLON.Vector3.Zero();
  61335. }
  61336. if (!ray.origin) {
  61337. ray.origin = BABYLON.Vector3.Zero();
  61338. }
  61339. if (length) {
  61340. ray.length = length;
  61341. }
  61342. if (!meshSpaceOrigin) {
  61343. meshSpaceOrigin = BABYLON.Vector3.Zero();
  61344. }
  61345. if (!meshSpaceDirection) {
  61346. // -1 so that this will work with Mesh.lookAt
  61347. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  61348. }
  61349. if (!this._meshSpaceDirection) {
  61350. this._meshSpaceDirection = meshSpaceDirection.clone();
  61351. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  61352. }
  61353. else {
  61354. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  61355. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  61356. }
  61357. if (!this._updateToMeshFunction) {
  61358. this._updateToMeshFunction = this._updateToMesh.bind(this);
  61359. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  61360. }
  61361. this._updateToMesh();
  61362. };
  61363. RayHelper.prototype.detachFromMesh = function () {
  61364. if (this._attachedToMesh) {
  61365. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  61366. this._attachedToMesh = null;
  61367. this._updateToMeshFunction = null;
  61368. }
  61369. };
  61370. RayHelper.prototype._updateToMesh = function () {
  61371. var ray = this.ray;
  61372. if (this._attachedToMesh._isDisposed) {
  61373. this.detachFromMesh();
  61374. return;
  61375. }
  61376. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61377. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61378. };
  61379. RayHelper.prototype.dispose = function () {
  61380. this.hide();
  61381. this.detachFromMesh();
  61382. this.ray = null;
  61383. };
  61384. return RayHelper;
  61385. }());
  61386. BABYLON.RayHelper = RayHelper;
  61387. })(BABYLON || (BABYLON = {}));
  61388. //# sourceMappingURL=babylon.rayHelper.js.map
  61389. var BABYLON;
  61390. (function (BABYLON) {
  61391. var DebugLayer = (function () {
  61392. function DebugLayer(scene) {
  61393. this._scene = scene;
  61394. }
  61395. /** Creates the inspector window. */
  61396. DebugLayer.prototype._createInspector = function (config) {
  61397. if (config === void 0) { config = {}; }
  61398. var popup = config.popup || false;
  61399. var initialTab = config.initialTab || 0;
  61400. var parentElement = config.parentElement || null;
  61401. if (!this._inspector) {
  61402. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61403. } // else nothing to do,; instance is already existing
  61404. };
  61405. DebugLayer.prototype.isVisible = function () {
  61406. if (!this._inspector) {
  61407. return false;
  61408. }
  61409. return true;
  61410. };
  61411. DebugLayer.prototype.hide = function () {
  61412. if (this._inspector) {
  61413. try {
  61414. this._inspector.dispose();
  61415. }
  61416. catch (e) {
  61417. // If the inspector has been removed directly from the inspector tool
  61418. }
  61419. this._inspector = null;
  61420. }
  61421. };
  61422. DebugLayer.prototype.show = function (config) {
  61423. if (config === void 0) { config = {}; }
  61424. if (typeof INSPECTOR == 'undefined') {
  61425. // Load inspector and add it to the DOM
  61426. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  61427. }
  61428. else {
  61429. // Otherwise creates the inspector
  61430. this._createInspector(config);
  61431. }
  61432. };
  61433. return DebugLayer;
  61434. }());
  61435. // Get protocol used - http or https
  61436. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61437. BABYLON.DebugLayer = DebugLayer;
  61438. })(BABYLON || (BABYLON = {}));
  61439. //# sourceMappingURL=babylon.debugLayer.js.map
  61440. var BABYLON;
  61441. (function (BABYLON) {
  61442. var Debug;
  61443. (function (Debug) {
  61444. var PhysicsViewer = (function () {
  61445. function PhysicsViewer(scene) {
  61446. this._impostors = [];
  61447. this._meshes = [];
  61448. this._numMeshes = 0;
  61449. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61450. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  61451. }
  61452. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61453. var plugin = this._physicsEnginePlugin;
  61454. for (var i = 0; i < this._numMeshes; i++) {
  61455. if (this._impostors[i].isDisposed) {
  61456. this.hideImpostor(this._impostors[i--]);
  61457. }
  61458. else {
  61459. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  61460. }
  61461. }
  61462. };
  61463. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61464. for (var i = 0; i < this._numMeshes; i++) {
  61465. if (this._impostors[i] == impostor) {
  61466. return;
  61467. }
  61468. }
  61469. var debugMesh = this._getDebugMesh(impostor, this._scene);
  61470. if (debugMesh) {
  61471. this._impostors[this._numMeshes] = impostor;
  61472. this._meshes[this._numMeshes] = debugMesh;
  61473. if (this._numMeshes === 0) {
  61474. this._renderFunction = this._updateDebugMeshes.bind(this);
  61475. this._scene.registerBeforeRender(this._renderFunction);
  61476. }
  61477. this._numMeshes++;
  61478. }
  61479. };
  61480. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61481. var removed = false;
  61482. for (var i = 0; i < this._numMeshes; i++) {
  61483. if (this._impostors[i] == impostor) {
  61484. this._scene.removeMesh(this._meshes[i]);
  61485. this._meshes[i].dispose();
  61486. this._numMeshes--;
  61487. if (this._numMeshes > 0) {
  61488. this._meshes[i] = this._meshes[this._numMeshes];
  61489. this._impostors[i] = this._impostors[this._numMeshes];
  61490. this._meshes[this._numMeshes] = null;
  61491. this._impostors[this._numMeshes] = null;
  61492. }
  61493. else {
  61494. this._meshes[0] = null;
  61495. this._impostors[0] = null;
  61496. }
  61497. removed = true;
  61498. break;
  61499. }
  61500. }
  61501. if (removed && this._numMeshes === 0) {
  61502. this._scene.unregisterBeforeRender(this._renderFunction);
  61503. }
  61504. };
  61505. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  61506. if (!this._debugMaterial) {
  61507. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  61508. this._debugMaterial.wireframe = true;
  61509. }
  61510. return this._debugMaterial;
  61511. };
  61512. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  61513. if (!this._debugBoxMesh) {
  61514. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  61515. this._debugBoxMesh.renderingGroupId = 1;
  61516. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61517. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  61518. scene.removeMesh(this._debugBoxMesh);
  61519. }
  61520. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  61521. };
  61522. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  61523. if (!this._debugSphereMesh) {
  61524. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  61525. this._debugSphereMesh.renderingGroupId = 1;
  61526. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61527. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  61528. scene.removeMesh(this._debugSphereMesh);
  61529. }
  61530. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  61531. };
  61532. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  61533. var body = impostor.physicsBody;
  61534. var shape = body.shapes[0];
  61535. var mesh;
  61536. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  61537. mesh = this._getDebugBoxMesh(scene);
  61538. impostor.getBoxSizeToRef(mesh.scaling);
  61539. }
  61540. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  61541. mesh = this._getDebugSphereMesh(scene);
  61542. var radius = impostor.getRadius();
  61543. mesh.scaling.x = radius * 2;
  61544. mesh.scaling.y = radius * 2;
  61545. mesh.scaling.z = radius * 2;
  61546. }
  61547. return mesh;
  61548. };
  61549. PhysicsViewer.prototype.dispose = function () {
  61550. for (var i = 0; i < this._numMeshes; i++) {
  61551. this.hideImpostor(this._impostors[i]);
  61552. }
  61553. if (this._debugBoxMesh) {
  61554. this._debugBoxMesh.dispose();
  61555. }
  61556. if (this._debugSphereMesh) {
  61557. this._debugSphereMesh.dispose();
  61558. }
  61559. if (this._debugMaterial) {
  61560. this._debugMaterial.dispose();
  61561. }
  61562. this._impostors.length = 0;
  61563. this._scene = null;
  61564. this._physicsEnginePlugin = null;
  61565. };
  61566. return PhysicsViewer;
  61567. }());
  61568. Debug.PhysicsViewer = PhysicsViewer;
  61569. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61570. })(BABYLON || (BABYLON = {}));
  61571. //# sourceMappingURL=babylon.physicsViewer.js.map
  61572. var BABYLON;
  61573. (function (BABYLON) {
  61574. var BoundingBoxRenderer = (function () {
  61575. function BoundingBoxRenderer(scene) {
  61576. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61577. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61578. this.showBackLines = true;
  61579. this.renderList = new BABYLON.SmartArray(32);
  61580. this._vertexBuffers = {};
  61581. this._scene = scene;
  61582. }
  61583. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61584. if (this._colorShader) {
  61585. return;
  61586. }
  61587. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  61588. attributes: [BABYLON.VertexBuffer.PositionKind],
  61589. uniforms: ["world", "viewProjection", "color"]
  61590. });
  61591. var engine = this._scene.getEngine();
  61592. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  61593. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61594. 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]);
  61595. };
  61596. BoundingBoxRenderer.prototype.reset = function () {
  61597. this.renderList.reset();
  61598. };
  61599. BoundingBoxRenderer.prototype.render = function () {
  61600. if (this.renderList.length === 0) {
  61601. return;
  61602. }
  61603. this._prepareRessources();
  61604. if (!this._colorShader.isReady()) {
  61605. return;
  61606. }
  61607. var engine = this._scene.getEngine();
  61608. engine.setDepthWrite(false);
  61609. this._colorShader._preBind();
  61610. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61611. var boundingBox = this.renderList.data[boundingBoxIndex];
  61612. var min = boundingBox.minimum;
  61613. var max = boundingBox.maximum;
  61614. var diff = max.subtract(min);
  61615. var median = min.add(diff.scale(0.5));
  61616. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61617. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61618. .multiply(boundingBox.getWorldMatrix());
  61619. // VBOs
  61620. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61621. if (this.showBackLines) {
  61622. // Back
  61623. engine.setDepthFunctionToGreaterOrEqual();
  61624. this._scene.resetCachedMaterial();
  61625. this._colorShader.setColor4("color", this.backColor.toColor4());
  61626. this._colorShader.bind(worldMatrix);
  61627. // Draw order
  61628. engine.draw(false, 0, 24);
  61629. }
  61630. // Front
  61631. engine.setDepthFunctionToLess();
  61632. this._scene.resetCachedMaterial();
  61633. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61634. this._colorShader.bind(worldMatrix);
  61635. // Draw order
  61636. engine.draw(false, 0, 24);
  61637. }
  61638. this._colorShader.unbind();
  61639. engine.setDepthFunctionToLessOrEqual();
  61640. engine.setDepthWrite(true);
  61641. };
  61642. BoundingBoxRenderer.prototype.dispose = function () {
  61643. if (!this._colorShader) {
  61644. return;
  61645. }
  61646. this.renderList.dispose();
  61647. this._colorShader.dispose();
  61648. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61649. if (buffer) {
  61650. buffer.dispose();
  61651. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61652. }
  61653. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61654. };
  61655. return BoundingBoxRenderer;
  61656. }());
  61657. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61658. })(BABYLON || (BABYLON = {}));
  61659. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61660. var BABYLON;
  61661. (function (BABYLON) {
  61662. var MorphTarget = (function () {
  61663. function MorphTarget(name, influence) {
  61664. if (influence === void 0) { influence = 0; }
  61665. this.name = name;
  61666. this.animations = new Array();
  61667. this.onInfluenceChanged = new BABYLON.Observable();
  61668. this.influence = influence;
  61669. }
  61670. Object.defineProperty(MorphTarget.prototype, "influence", {
  61671. get: function () {
  61672. return this._influence;
  61673. },
  61674. set: function (influence) {
  61675. if (this._influence === influence) {
  61676. return;
  61677. }
  61678. var previous = this._influence;
  61679. this._influence = influence;
  61680. if (this.onInfluenceChanged.hasObservers) {
  61681. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  61682. }
  61683. },
  61684. enumerable: true,
  61685. configurable: true
  61686. });
  61687. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  61688. get: function () {
  61689. return this._normals !== undefined;
  61690. },
  61691. enumerable: true,
  61692. configurable: true
  61693. });
  61694. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  61695. get: function () {
  61696. return this._tangents !== undefined;
  61697. },
  61698. enumerable: true,
  61699. configurable: true
  61700. });
  61701. MorphTarget.prototype.setPositions = function (data) {
  61702. this._positions = new Float32Array(data);
  61703. };
  61704. MorphTarget.prototype.getPositions = function () {
  61705. return this._positions;
  61706. };
  61707. MorphTarget.prototype.setNormals = function (data) {
  61708. this._normals = new Float32Array(data);
  61709. };
  61710. MorphTarget.prototype.getNormals = function () {
  61711. return this._normals;
  61712. };
  61713. MorphTarget.prototype.setTangents = function (data) {
  61714. this._tangents = new Float32Array(data);
  61715. };
  61716. MorphTarget.prototype.getTangents = function () {
  61717. return this._tangents;
  61718. };
  61719. /**
  61720. * Serializes the current target into a Serialization object.
  61721. * Returns the serialized object.
  61722. */
  61723. MorphTarget.prototype.serialize = function () {
  61724. var serializationObject = {};
  61725. serializationObject.name = this.name;
  61726. serializationObject.influence = this.influence;
  61727. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  61728. if (this.hasNormals) {
  61729. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  61730. }
  61731. if (this.hasTangents) {
  61732. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  61733. }
  61734. return serializationObject;
  61735. };
  61736. // Statics
  61737. MorphTarget.Parse = function (serializationObject) {
  61738. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  61739. result.setPositions(serializationObject.positions);
  61740. if (serializationObject.normals) {
  61741. result.setNormals(serializationObject.normals);
  61742. }
  61743. if (serializationObject.tangents) {
  61744. result.setTangents(serializationObject.tangents);
  61745. }
  61746. return result;
  61747. };
  61748. MorphTarget.FromMesh = function (mesh, name, influence) {
  61749. if (!name) {
  61750. name = mesh.name;
  61751. }
  61752. var result = new MorphTarget(name, influence);
  61753. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  61754. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61755. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  61756. }
  61757. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  61758. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  61759. }
  61760. return result;
  61761. };
  61762. return MorphTarget;
  61763. }());
  61764. BABYLON.MorphTarget = MorphTarget;
  61765. })(BABYLON || (BABYLON = {}));
  61766. //# sourceMappingURL=babylon.morphTarget.js.map
  61767. var BABYLON;
  61768. (function (BABYLON) {
  61769. var MorphTargetManager = (function () {
  61770. function MorphTargetManager(scene) {
  61771. this._targets = new Array();
  61772. this._targetObservable = new Array();
  61773. this._activeTargets = new BABYLON.SmartArray(16);
  61774. this._supportsNormals = false;
  61775. this._supportsTangents = false;
  61776. this._vertexCount = 0;
  61777. this._uniqueId = 0;
  61778. this._tempInfluences = new Array();
  61779. if (!scene) {
  61780. scene = BABYLON.Engine.LastCreatedScene;
  61781. }
  61782. this._scene = scene;
  61783. this._scene.morphTargetManagers.push(this);
  61784. this._uniqueId = scene.getUniqueId();
  61785. }
  61786. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  61787. get: function () {
  61788. return this._uniqueId;
  61789. },
  61790. enumerable: true,
  61791. configurable: true
  61792. });
  61793. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  61794. get: function () {
  61795. return this._vertexCount;
  61796. },
  61797. enumerable: true,
  61798. configurable: true
  61799. });
  61800. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  61801. get: function () {
  61802. return this._supportsNormals;
  61803. },
  61804. enumerable: true,
  61805. configurable: true
  61806. });
  61807. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  61808. get: function () {
  61809. return this._supportsTangents;
  61810. },
  61811. enumerable: true,
  61812. configurable: true
  61813. });
  61814. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  61815. get: function () {
  61816. return this._targets.length;
  61817. },
  61818. enumerable: true,
  61819. configurable: true
  61820. });
  61821. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  61822. get: function () {
  61823. return this._activeTargets.length;
  61824. },
  61825. enumerable: true,
  61826. configurable: true
  61827. });
  61828. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  61829. get: function () {
  61830. return this._influences;
  61831. },
  61832. enumerable: true,
  61833. configurable: true
  61834. });
  61835. MorphTargetManager.prototype.getActiveTarget = function (index) {
  61836. return this._activeTargets.data[index];
  61837. };
  61838. MorphTargetManager.prototype.getTarget = function (index) {
  61839. return this._targets[index];
  61840. };
  61841. MorphTargetManager.prototype.addTarget = function (target) {
  61842. var _this = this;
  61843. if (this._vertexCount) {
  61844. if (this._vertexCount !== target.getPositions().length / 3) {
  61845. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  61846. return;
  61847. }
  61848. }
  61849. this._targets.push(target);
  61850. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  61851. _this._syncActiveTargets(needUpdate);
  61852. }));
  61853. this._syncActiveTargets(true);
  61854. };
  61855. MorphTargetManager.prototype.removeTarget = function (target) {
  61856. var index = this._targets.indexOf(target);
  61857. if (index >= 0) {
  61858. this._targets.splice(index, 1);
  61859. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  61860. this._vertexCount = 0;
  61861. this._syncActiveTargets(true);
  61862. }
  61863. };
  61864. /**
  61865. * Serializes the current manager into a Serialization object.
  61866. * Returns the serialized object.
  61867. */
  61868. MorphTargetManager.prototype.serialize = function () {
  61869. var serializationObject = {};
  61870. serializationObject.id = this.uniqueId;
  61871. serializationObject.targets = [];
  61872. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  61873. var target = _a[_i];
  61874. serializationObject.targets.push(target.serialize());
  61875. }
  61876. return serializationObject;
  61877. };
  61878. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  61879. this._syncActiveTargets(needUpdate);
  61880. };
  61881. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  61882. var influenceCount = 0;
  61883. this._activeTargets.reset();
  61884. this._supportsNormals = true;
  61885. this._supportsTangents = true;
  61886. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  61887. var target = _a[_i];
  61888. if (target.influence > 0) {
  61889. this._activeTargets.push(target);
  61890. this._tempInfluences[influenceCount++] = target.influence;
  61891. this._supportsNormals = this._supportsNormals && target.hasNormals;
  61892. this._supportsTangents = this._supportsTangents && target.hasTangents;
  61893. if (this._vertexCount === 0) {
  61894. this._vertexCount = target.getPositions().length / 3;
  61895. }
  61896. }
  61897. }
  61898. if (!this._influences || this._influences.length !== influenceCount) {
  61899. this._influences = new Float32Array(influenceCount);
  61900. }
  61901. for (var index = 0; index < influenceCount; index++) {
  61902. this._influences[index] = this._tempInfluences[index];
  61903. }
  61904. if (needUpdate) {
  61905. // Flag meshes as dirty to resync with the active targets
  61906. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  61907. var mesh = _c[_b];
  61908. if (mesh.morphTargetManager === this) {
  61909. mesh._syncGeometryWithMorphTargetManager();
  61910. }
  61911. }
  61912. }
  61913. };
  61914. // Statics
  61915. MorphTargetManager.Parse = function (serializationObject, scene) {
  61916. var result = new MorphTargetManager(scene);
  61917. result._uniqueId = serializationObject.id;
  61918. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  61919. var targetData = _a[_i];
  61920. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  61921. }
  61922. return result;
  61923. };
  61924. return MorphTargetManager;
  61925. }());
  61926. BABYLON.MorphTargetManager = MorphTargetManager;
  61927. })(BABYLON || (BABYLON = {}));
  61928. //# sourceMappingURL=babylon.morphTargetManager.js.map
  61929. var BABYLON;
  61930. (function (BABYLON) {
  61931. /**
  61932. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  61933. * It can help converting any input color in a desired output one. This can then be used to create effects
  61934. * from sepia, black and white to sixties or futuristic rendering...
  61935. *
  61936. * The only supported format is currently 3dl.
  61937. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  61938. */
  61939. var ColorGradingTexture = (function (_super) {
  61940. __extends(ColorGradingTexture, _super);
  61941. /**
  61942. * Instantiates a ColorGradingTexture from the following parameters.
  61943. *
  61944. * @param url The location of the color gradind data (currently only supporting 3dl)
  61945. * @param scene The scene the texture will be used in
  61946. */
  61947. function ColorGradingTexture(url, scene) {
  61948. var _this = _super.call(this, scene) || this;
  61949. if (!url) {
  61950. return _this;
  61951. }
  61952. _this._textureMatrix = BABYLON.Matrix.Identity();
  61953. _this.name = url;
  61954. _this.url = url;
  61955. _this.hasAlpha = false;
  61956. _this.isCube = false;
  61957. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61958. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61959. _this.anisotropicFilteringLevel = 1;
  61960. _this._texture = _this._getFromCache(url, true);
  61961. if (!_this._texture) {
  61962. if (!scene.useDelayedTextureLoading) {
  61963. _this.loadTexture();
  61964. }
  61965. else {
  61966. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61967. }
  61968. }
  61969. return _this;
  61970. }
  61971. /**
  61972. * Returns the texture matrix used in most of the material.
  61973. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  61974. */
  61975. ColorGradingTexture.prototype.getTextureMatrix = function () {
  61976. return this._textureMatrix;
  61977. };
  61978. /**
  61979. * Occurs when the file being loaded is a .3dl LUT file.
  61980. */
  61981. ColorGradingTexture.prototype.load3dlTexture = function () {
  61982. var _this = this;
  61983. var mipLevels = 0;
  61984. var floatArrayView = null;
  61985. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61986. this._texture = texture;
  61987. var callback = function (text) {
  61988. var data;
  61989. var tempData;
  61990. var line;
  61991. var lines = text.split('\n');
  61992. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  61993. var maxColor = 0;
  61994. for (var i = 0; i < lines.length; i++) {
  61995. line = lines[i];
  61996. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  61997. continue;
  61998. if (line.indexOf('#') === 0)
  61999. continue;
  62000. var words = line.split(" ");
  62001. if (size === 0) {
  62002. // Number of space + one
  62003. size = words.length;
  62004. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  62005. tempData = new Float32Array(size * size * size * 4);
  62006. continue;
  62007. }
  62008. if (size != 0) {
  62009. var r = Math.max(parseInt(words[0]), 0);
  62010. var g = Math.max(parseInt(words[1]), 0);
  62011. var b = Math.max(parseInt(words[2]), 0);
  62012. maxColor = Math.max(r, maxColor);
  62013. maxColor = Math.max(g, maxColor);
  62014. maxColor = Math.max(b, maxColor);
  62015. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  62016. tempData[pixelStorageIndex + 0] = r;
  62017. tempData[pixelStorageIndex + 1] = g;
  62018. tempData[pixelStorageIndex + 2] = b;
  62019. pixelIndexSlice++;
  62020. if (pixelIndexSlice % size == 0) {
  62021. pixelIndexH++;
  62022. pixelIndexSlice = 0;
  62023. if (pixelIndexH % size == 0) {
  62024. pixelIndexW++;
  62025. pixelIndexH = 0;
  62026. }
  62027. }
  62028. }
  62029. }
  62030. for (var i = 0; i < tempData.length; i++) {
  62031. if (i > 0 && (i + 1) % 4 === 0) {
  62032. data[i] = 255;
  62033. }
  62034. else {
  62035. var value = tempData[i];
  62036. data[i] = (value / maxColor * 255);
  62037. }
  62038. }
  62039. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  62040. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  62041. };
  62042. BABYLON.Tools.LoadFile(this.url, callback);
  62043. return this._texture;
  62044. };
  62045. /**
  62046. * Starts the loading process of the texture.
  62047. */
  62048. ColorGradingTexture.prototype.loadTexture = function () {
  62049. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  62050. this.load3dlTexture();
  62051. }
  62052. };
  62053. /**
  62054. * Clones the color gradind texture.
  62055. */
  62056. ColorGradingTexture.prototype.clone = function () {
  62057. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  62058. // Base texture
  62059. newTexture.level = this.level;
  62060. return newTexture;
  62061. };
  62062. /**
  62063. * Called during delayed load for textures.
  62064. */
  62065. ColorGradingTexture.prototype.delayLoad = function () {
  62066. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62067. return;
  62068. }
  62069. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62070. this._texture = this._getFromCache(this.url, true);
  62071. if (!this._texture) {
  62072. this.loadTexture();
  62073. }
  62074. };
  62075. /**
  62076. * Parses a color grading texture serialized by Babylon.
  62077. * @param parsedTexture The texture information being parsedTexture
  62078. * @param scene The scene to load the texture in
  62079. * @param rootUrl The root url of the data assets to load
  62080. * @return A color gradind texture
  62081. */
  62082. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62083. var texture = null;
  62084. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  62085. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  62086. texture.name = parsedTexture.name;
  62087. texture.level = parsedTexture.level;
  62088. }
  62089. return texture;
  62090. };
  62091. /**
  62092. * Serializes the LUT texture to json format.
  62093. */
  62094. ColorGradingTexture.prototype.serialize = function () {
  62095. if (!this.name) {
  62096. return null;
  62097. }
  62098. var serializationObject = {};
  62099. serializationObject.name = this.name;
  62100. serializationObject.level = this.level;
  62101. serializationObject.customType = "BABYLON.ColorGradingTexture";
  62102. return serializationObject;
  62103. };
  62104. return ColorGradingTexture;
  62105. }(BABYLON.BaseTexture));
  62106. /**
  62107. * Empty line regex stored for GC.
  62108. */
  62109. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  62110. BABYLON.ColorGradingTexture = ColorGradingTexture;
  62111. })(BABYLON || (BABYLON = {}));
  62112. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  62113. var BABYLON;
  62114. (function (BABYLON) {
  62115. /**
  62116. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  62117. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  62118. * 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;
  62119. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  62120. */
  62121. var ColorCurves = (function () {
  62122. function ColorCurves() {
  62123. this._dirty = true;
  62124. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  62125. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  62126. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  62127. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  62128. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  62129. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  62130. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  62131. this._globalHue = 30;
  62132. this._globalDensity = 0;
  62133. this._globalSaturation = 0;
  62134. this._globalExposure = 0;
  62135. this._highlightsHue = 30;
  62136. this._highlightsDensity = 0;
  62137. this._highlightsSaturation = 0;
  62138. this._highlightsExposure = 0;
  62139. this._midtonesHue = 30;
  62140. this._midtonesDensity = 0;
  62141. this._midtonesSaturation = 0;
  62142. this._midtonesExposure = 0;
  62143. this._shadowsHue = 30;
  62144. this._shadowsDensity = 0;
  62145. this._shadowsSaturation = 0;
  62146. this._shadowsExposure = 0;
  62147. }
  62148. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  62149. /**
  62150. * Gets the global Hue value.
  62151. * 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).
  62152. */
  62153. get: function () {
  62154. return this._globalHue;
  62155. },
  62156. /**
  62157. * Sets the global Hue value.
  62158. * 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).
  62159. */
  62160. set: function (value) {
  62161. this._globalHue = value;
  62162. this._dirty = true;
  62163. },
  62164. enumerable: true,
  62165. configurable: true
  62166. });
  62167. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  62168. /**
  62169. * Gets the global Density value.
  62170. * 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.
  62171. * Values less than zero provide a filter of opposite hue.
  62172. */
  62173. get: function () {
  62174. return this._globalDensity;
  62175. },
  62176. /**
  62177. * Sets the global Density value.
  62178. * 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.
  62179. * Values less than zero provide a filter of opposite hue.
  62180. */
  62181. set: function (value) {
  62182. this._globalDensity = value;
  62183. this._dirty = true;
  62184. },
  62185. enumerable: true,
  62186. configurable: true
  62187. });
  62188. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  62189. /**
  62190. * Gets the global Saturation value.
  62191. * 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.
  62192. */
  62193. get: function () {
  62194. return this._globalSaturation;
  62195. },
  62196. /**
  62197. * Sets the global Saturation value.
  62198. * 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.
  62199. */
  62200. set: function (value) {
  62201. this._globalSaturation = value;
  62202. this._dirty = true;
  62203. },
  62204. enumerable: true,
  62205. configurable: true
  62206. });
  62207. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  62208. /**
  62209. * Gets the highlights Hue value.
  62210. * 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).
  62211. */
  62212. get: function () {
  62213. return this._highlightsHue;
  62214. },
  62215. /**
  62216. * Sets the highlights Hue value.
  62217. * 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).
  62218. */
  62219. set: function (value) {
  62220. this._highlightsHue = value;
  62221. this._dirty = true;
  62222. },
  62223. enumerable: true,
  62224. configurable: true
  62225. });
  62226. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  62227. /**
  62228. * Gets the highlights Density value.
  62229. * 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.
  62230. * Values less than zero provide a filter of opposite hue.
  62231. */
  62232. get: function () {
  62233. return this._highlightsDensity;
  62234. },
  62235. /**
  62236. * Sets the highlights Density value.
  62237. * 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.
  62238. * Values less than zero provide a filter of opposite hue.
  62239. */
  62240. set: function (value) {
  62241. this._highlightsDensity = value;
  62242. this._dirty = true;
  62243. },
  62244. enumerable: true,
  62245. configurable: true
  62246. });
  62247. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  62248. /**
  62249. * Gets the highlights Saturation value.
  62250. * 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.
  62251. */
  62252. get: function () {
  62253. return this._highlightsSaturation;
  62254. },
  62255. /**
  62256. * Sets the highlights Saturation value.
  62257. * 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.
  62258. */
  62259. set: function (value) {
  62260. this._highlightsSaturation = value;
  62261. this._dirty = true;
  62262. },
  62263. enumerable: true,
  62264. configurable: true
  62265. });
  62266. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  62267. /**
  62268. * Gets the highlights Exposure value.
  62269. * 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.
  62270. */
  62271. get: function () {
  62272. return this._highlightsExposure;
  62273. },
  62274. /**
  62275. * Sets the highlights Exposure value.
  62276. * 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.
  62277. */
  62278. set: function (value) {
  62279. this._highlightsExposure = value;
  62280. this._dirty = true;
  62281. },
  62282. enumerable: true,
  62283. configurable: true
  62284. });
  62285. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  62286. /**
  62287. * Gets the midtones Hue value.
  62288. * 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).
  62289. */
  62290. get: function () {
  62291. return this._midtonesHue;
  62292. },
  62293. /**
  62294. * Sets the midtones Hue value.
  62295. * 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).
  62296. */
  62297. set: function (value) {
  62298. this._midtonesHue = value;
  62299. this._dirty = true;
  62300. },
  62301. enumerable: true,
  62302. configurable: true
  62303. });
  62304. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  62305. /**
  62306. * Gets the midtones Density value.
  62307. * 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.
  62308. * Values less than zero provide a filter of opposite hue.
  62309. */
  62310. get: function () {
  62311. return this._midtonesDensity;
  62312. },
  62313. /**
  62314. * Sets the midtones Density value.
  62315. * 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.
  62316. * Values less than zero provide a filter of opposite hue.
  62317. */
  62318. set: function (value) {
  62319. this._midtonesDensity = value;
  62320. this._dirty = true;
  62321. },
  62322. enumerable: true,
  62323. configurable: true
  62324. });
  62325. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  62326. /**
  62327. * Gets the midtones Saturation value.
  62328. * 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.
  62329. */
  62330. get: function () {
  62331. return this._midtonesSaturation;
  62332. },
  62333. /**
  62334. * Sets the midtones Saturation value.
  62335. * 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.
  62336. */
  62337. set: function (value) {
  62338. this._midtonesSaturation = value;
  62339. this._dirty = true;
  62340. },
  62341. enumerable: true,
  62342. configurable: true
  62343. });
  62344. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  62345. /**
  62346. * Gets the midtones Exposure value.
  62347. * 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.
  62348. */
  62349. get: function () {
  62350. return this._midtonesExposure;
  62351. },
  62352. /**
  62353. * Sets the midtones Exposure value.
  62354. * 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.
  62355. */
  62356. set: function (value) {
  62357. this._midtonesExposure = value;
  62358. this._dirty = true;
  62359. },
  62360. enumerable: true,
  62361. configurable: true
  62362. });
  62363. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  62364. /**
  62365. * Gets the shadows Hue value.
  62366. * 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).
  62367. */
  62368. get: function () {
  62369. return this._shadowsHue;
  62370. },
  62371. /**
  62372. * Sets the shadows Hue value.
  62373. * 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).
  62374. */
  62375. set: function (value) {
  62376. this._shadowsHue = value;
  62377. this._dirty = true;
  62378. },
  62379. enumerable: true,
  62380. configurable: true
  62381. });
  62382. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  62383. /**
  62384. * Gets the shadows Density value.
  62385. * 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.
  62386. * Values less than zero provide a filter of opposite hue.
  62387. */
  62388. get: function () {
  62389. return this._shadowsDensity;
  62390. },
  62391. /**
  62392. * Sets the shadows Density value.
  62393. * 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.
  62394. * Values less than zero provide a filter of opposite hue.
  62395. */
  62396. set: function (value) {
  62397. this._shadowsDensity = value;
  62398. this._dirty = true;
  62399. },
  62400. enumerable: true,
  62401. configurable: true
  62402. });
  62403. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  62404. /**
  62405. * Gets the shadows Saturation value.
  62406. * 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.
  62407. */
  62408. get: function () {
  62409. return this._shadowsSaturation;
  62410. },
  62411. /**
  62412. * Sets the shadows Saturation value.
  62413. * 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.
  62414. */
  62415. set: function (value) {
  62416. this._shadowsSaturation = value;
  62417. this._dirty = true;
  62418. },
  62419. enumerable: true,
  62420. configurable: true
  62421. });
  62422. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  62423. /**
  62424. * Gets the shadows Exposure value.
  62425. * 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.
  62426. */
  62427. get: function () {
  62428. return this._shadowsExposure;
  62429. },
  62430. /**
  62431. * Sets the shadows Exposure value.
  62432. * 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.
  62433. */
  62434. set: function (value) {
  62435. this._shadowsExposure = value;
  62436. this._dirty = true;
  62437. },
  62438. enumerable: true,
  62439. configurable: true
  62440. });
  62441. /**
  62442. * Binds the color curves to the shader.
  62443. * @param colorCurves The color curve to bind
  62444. * @param effect The effect to bind to
  62445. */
  62446. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  62447. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  62448. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  62449. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  62450. if (colorCurves._dirty) {
  62451. colorCurves._dirty = false;
  62452. // Fill in global info.
  62453. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  62454. // Compute highlights info.
  62455. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  62456. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  62457. // Compute midtones info.
  62458. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  62459. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  62460. // Compute shadows info.
  62461. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  62462. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  62463. // Compute deltas (neutral is midtones).
  62464. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  62465. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  62466. }
  62467. if (effect) {
  62468. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  62469. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  62470. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  62471. }
  62472. };
  62473. /**
  62474. * Prepare the list of uniforms associated with the ColorCurves effects.
  62475. * @param uniformsList The list of uniforms used in the effect
  62476. */
  62477. ColorCurves.PrepareUniforms = function (uniformsList) {
  62478. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  62479. };
  62480. /**
  62481. * Returns color grading data based on a hue, density, saturation and exposure value.
  62482. * @param filterHue The hue of the color filter.
  62483. * @param filterDensity The density of the color filter.
  62484. * @param saturation The saturation.
  62485. * @param exposure The exposure.
  62486. * @param result The result data container.
  62487. */
  62488. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  62489. if (hue == null) {
  62490. return;
  62491. }
  62492. hue = ColorCurves.clamp(hue, 0, 360);
  62493. density = ColorCurves.clamp(density, -100, 100);
  62494. saturation = ColorCurves.clamp(saturation, -100, 100);
  62495. exposure = ColorCurves.clamp(exposure, -100, 100);
  62496. // Remap the slider/config filter density with non-linear mapping and also scale by half
  62497. // so that the maximum filter density is only 50% control. This provides fine control
  62498. // for small values and reasonable range.
  62499. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  62500. density *= 0.5;
  62501. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  62502. if (density < 0) {
  62503. density *= -1;
  62504. hue = (hue + 180) % 360;
  62505. }
  62506. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  62507. result.scaleToRef(2, result);
  62508. result.a = 1 + 0.01 * saturation;
  62509. };
  62510. /**
  62511. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  62512. * @param value The input slider value in range [-100,100].
  62513. * @returns Adjusted value.
  62514. */
  62515. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  62516. value /= 100;
  62517. var x = Math.abs(value);
  62518. x = Math.pow(x, 2);
  62519. if (value < 0) {
  62520. x *= -1;
  62521. }
  62522. x *= 100;
  62523. return x;
  62524. };
  62525. /**
  62526. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  62527. * @param hue The hue (H) input.
  62528. * @param saturation The saturation (S) input.
  62529. * @param brightness The brightness (B) input.
  62530. * @result An RGBA color represented as Vector4.
  62531. */
  62532. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  62533. var h = ColorCurves.clamp(hue, 0, 360);
  62534. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  62535. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  62536. if (s === 0) {
  62537. result.r = v;
  62538. result.g = v;
  62539. result.b = v;
  62540. }
  62541. else {
  62542. // sector 0 to 5
  62543. h /= 60;
  62544. var i = Math.floor(h);
  62545. // fractional part of h
  62546. var f = h - i;
  62547. var p = v * (1 - s);
  62548. var q = v * (1 - s * f);
  62549. var t = v * (1 - s * (1 - f));
  62550. switch (i) {
  62551. case 0:
  62552. result.r = v;
  62553. result.g = t;
  62554. result.b = p;
  62555. break;
  62556. case 1:
  62557. result.r = q;
  62558. result.g = v;
  62559. result.b = p;
  62560. break;
  62561. case 2:
  62562. result.r = p;
  62563. result.g = v;
  62564. result.b = t;
  62565. break;
  62566. case 3:
  62567. result.r = p;
  62568. result.g = q;
  62569. result.b = v;
  62570. break;
  62571. case 4:
  62572. result.r = t;
  62573. result.g = p;
  62574. result.b = v;
  62575. break;
  62576. default:
  62577. result.r = v;
  62578. result.g = p;
  62579. result.b = q;
  62580. break;
  62581. }
  62582. }
  62583. result.a = 1;
  62584. };
  62585. /**
  62586. * Returns a value clamped between min and max
  62587. * @param value The value to clamp
  62588. * @param min The minimum of value
  62589. * @param max The maximum of value
  62590. * @returns The clamped value.
  62591. */
  62592. ColorCurves.clamp = function (value, min, max) {
  62593. return Math.min(Math.max(value, min), max);
  62594. };
  62595. /**
  62596. * Clones the current color curve instance.
  62597. * @return The cloned curves
  62598. */
  62599. ColorCurves.prototype.clone = function () {
  62600. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  62601. };
  62602. /**
  62603. * Serializes the current color curve instance to a json representation.
  62604. * @return a JSON representation
  62605. */
  62606. ColorCurves.prototype.serialize = function () {
  62607. return BABYLON.SerializationHelper.Serialize(this);
  62608. };
  62609. /**
  62610. * Parses the color curve from a json representation.
  62611. * @param source the JSON source to parse
  62612. * @return The parsed curves
  62613. */
  62614. ColorCurves.Parse = function (source) {
  62615. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  62616. };
  62617. return ColorCurves;
  62618. }());
  62619. __decorate([
  62620. BABYLON.serialize()
  62621. ], ColorCurves.prototype, "_globalHue", void 0);
  62622. __decorate([
  62623. BABYLON.serialize()
  62624. ], ColorCurves.prototype, "_globalDensity", void 0);
  62625. __decorate([
  62626. BABYLON.serialize()
  62627. ], ColorCurves.prototype, "_globalSaturation", void 0);
  62628. __decorate([
  62629. BABYLON.serialize()
  62630. ], ColorCurves.prototype, "_globalExposure", void 0);
  62631. __decorate([
  62632. BABYLON.serialize()
  62633. ], ColorCurves.prototype, "_highlightsHue", void 0);
  62634. __decorate([
  62635. BABYLON.serialize()
  62636. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  62637. __decorate([
  62638. BABYLON.serialize()
  62639. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  62640. __decorate([
  62641. BABYLON.serialize()
  62642. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  62643. __decorate([
  62644. BABYLON.serialize()
  62645. ], ColorCurves.prototype, "_midtonesHue", void 0);
  62646. __decorate([
  62647. BABYLON.serialize()
  62648. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  62649. __decorate([
  62650. BABYLON.serialize()
  62651. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  62652. __decorate([
  62653. BABYLON.serialize()
  62654. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  62655. BABYLON.ColorCurves = ColorCurves;
  62656. })(BABYLON || (BABYLON = {}));
  62657. //# sourceMappingURL=babylon.colorCurves.js.map
  62658. var BABYLON;
  62659. (function (BABYLON) {
  62660. var Octree = (function () {
  62661. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  62662. if (maxDepth === void 0) { maxDepth = 2; }
  62663. this.maxDepth = maxDepth;
  62664. this.dynamicContent = new Array();
  62665. this._maxBlockCapacity = maxBlockCapacity || 64;
  62666. this._selectionContent = new BABYLON.SmartArray(1024);
  62667. this._creationFunc = creationFunc;
  62668. }
  62669. // Methods
  62670. Octree.prototype.update = function (worldMin, worldMax, entries) {
  62671. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  62672. };
  62673. Octree.prototype.addMesh = function (entry) {
  62674. for (var index = 0; index < this.blocks.length; index++) {
  62675. var block = this.blocks[index];
  62676. block.addEntry(entry);
  62677. }
  62678. };
  62679. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  62680. this._selectionContent.reset();
  62681. for (var index = 0; index < this.blocks.length; index++) {
  62682. var block = this.blocks[index];
  62683. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  62684. }
  62685. if (allowDuplicate) {
  62686. this._selectionContent.concat(this.dynamicContent);
  62687. }
  62688. else {
  62689. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62690. }
  62691. return this._selectionContent;
  62692. };
  62693. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  62694. this._selectionContent.reset();
  62695. for (var index = 0; index < this.blocks.length; index++) {
  62696. var block = this.blocks[index];
  62697. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  62698. }
  62699. if (allowDuplicate) {
  62700. this._selectionContent.concat(this.dynamicContent);
  62701. }
  62702. else {
  62703. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62704. }
  62705. return this._selectionContent;
  62706. };
  62707. Octree.prototype.intersectsRay = function (ray) {
  62708. this._selectionContent.reset();
  62709. for (var index = 0; index < this.blocks.length; index++) {
  62710. var block = this.blocks[index];
  62711. block.intersectsRay(ray, this._selectionContent);
  62712. }
  62713. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62714. return this._selectionContent;
  62715. };
  62716. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  62717. target.blocks = new Array();
  62718. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  62719. // Segmenting space
  62720. for (var x = 0; x < 2; x++) {
  62721. for (var y = 0; y < 2; y++) {
  62722. for (var z = 0; z < 2; z++) {
  62723. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  62724. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  62725. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  62726. block.addEntries(entries);
  62727. target.blocks.push(block);
  62728. }
  62729. }
  62730. }
  62731. };
  62732. return Octree;
  62733. }());
  62734. Octree.CreationFuncForMeshes = function (entry, block) {
  62735. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  62736. block.entries.push(entry);
  62737. }
  62738. };
  62739. Octree.CreationFuncForSubMeshes = function (entry, block) {
  62740. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  62741. block.entries.push(entry);
  62742. }
  62743. };
  62744. BABYLON.Octree = Octree;
  62745. })(BABYLON || (BABYLON = {}));
  62746. //# sourceMappingURL=babylon.octree.js.map
  62747. var BABYLON;
  62748. (function (BABYLON) {
  62749. var OctreeBlock = (function () {
  62750. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  62751. this.entries = new Array();
  62752. this._boundingVectors = new Array();
  62753. this._capacity = capacity;
  62754. this._depth = depth;
  62755. this._maxDepth = maxDepth;
  62756. this._creationFunc = creationFunc;
  62757. this._minPoint = minPoint;
  62758. this._maxPoint = maxPoint;
  62759. this._boundingVectors.push(minPoint.clone());
  62760. this._boundingVectors.push(maxPoint.clone());
  62761. this._boundingVectors.push(minPoint.clone());
  62762. this._boundingVectors[2].x = maxPoint.x;
  62763. this._boundingVectors.push(minPoint.clone());
  62764. this._boundingVectors[3].y = maxPoint.y;
  62765. this._boundingVectors.push(minPoint.clone());
  62766. this._boundingVectors[4].z = maxPoint.z;
  62767. this._boundingVectors.push(maxPoint.clone());
  62768. this._boundingVectors[5].z = minPoint.z;
  62769. this._boundingVectors.push(maxPoint.clone());
  62770. this._boundingVectors[6].x = minPoint.x;
  62771. this._boundingVectors.push(maxPoint.clone());
  62772. this._boundingVectors[7].y = minPoint.y;
  62773. }
  62774. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  62775. // Property
  62776. get: function () {
  62777. return this._capacity;
  62778. },
  62779. enumerable: true,
  62780. configurable: true
  62781. });
  62782. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  62783. get: function () {
  62784. return this._minPoint;
  62785. },
  62786. enumerable: true,
  62787. configurable: true
  62788. });
  62789. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  62790. get: function () {
  62791. return this._maxPoint;
  62792. },
  62793. enumerable: true,
  62794. configurable: true
  62795. });
  62796. // Methods
  62797. OctreeBlock.prototype.addEntry = function (entry) {
  62798. if (this.blocks) {
  62799. for (var index = 0; index < this.blocks.length; index++) {
  62800. var block = this.blocks[index];
  62801. block.addEntry(entry);
  62802. }
  62803. return;
  62804. }
  62805. this._creationFunc(entry, this);
  62806. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  62807. this.createInnerBlocks();
  62808. }
  62809. };
  62810. OctreeBlock.prototype.addEntries = function (entries) {
  62811. for (var index = 0; index < entries.length; index++) {
  62812. var mesh = entries[index];
  62813. this.addEntry(mesh);
  62814. }
  62815. };
  62816. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  62817. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  62818. if (this.blocks) {
  62819. for (var index = 0; index < this.blocks.length; index++) {
  62820. var block = this.blocks[index];
  62821. block.select(frustumPlanes, selection, allowDuplicate);
  62822. }
  62823. return;
  62824. }
  62825. if (allowDuplicate) {
  62826. selection.concat(this.entries);
  62827. }
  62828. else {
  62829. selection.concatWithNoDuplicate(this.entries);
  62830. }
  62831. }
  62832. };
  62833. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  62834. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  62835. if (this.blocks) {
  62836. for (var index = 0; index < this.blocks.length; index++) {
  62837. var block = this.blocks[index];
  62838. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  62839. }
  62840. return;
  62841. }
  62842. if (allowDuplicate) {
  62843. selection.concat(this.entries);
  62844. }
  62845. else {
  62846. selection.concatWithNoDuplicate(this.entries);
  62847. }
  62848. }
  62849. };
  62850. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  62851. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  62852. if (this.blocks) {
  62853. for (var index = 0; index < this.blocks.length; index++) {
  62854. var block = this.blocks[index];
  62855. block.intersectsRay(ray, selection);
  62856. }
  62857. return;
  62858. }
  62859. selection.concatWithNoDuplicate(this.entries);
  62860. }
  62861. };
  62862. OctreeBlock.prototype.createInnerBlocks = function () {
  62863. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  62864. };
  62865. return OctreeBlock;
  62866. }());
  62867. BABYLON.OctreeBlock = OctreeBlock;
  62868. })(BABYLON || (BABYLON = {}));
  62869. //# sourceMappingURL=babylon.octreeBlock.js.map
  62870. var BABYLON;
  62871. (function (BABYLON) {
  62872. var SIMDVector3 = (function () {
  62873. function SIMDVector3() {
  62874. }
  62875. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  62876. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  62877. };
  62878. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  62879. var m = transformation.m;
  62880. var m0 = SIMD.Float32x4.load(m, 0);
  62881. var m1 = SIMD.Float32x4.load(m, 4);
  62882. var m2 = SIMD.Float32x4.load(m, 8);
  62883. var m3 = SIMD.Float32x4.load(m, 12);
  62884. 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));
  62885. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  62886. result.x = SIMD.Float32x4.extractLane(r, 0);
  62887. result.y = SIMD.Float32x4.extractLane(r, 1);
  62888. result.z = SIMD.Float32x4.extractLane(r, 2);
  62889. };
  62890. return SIMDVector3;
  62891. }());
  62892. var SIMDMatrix = (function () {
  62893. function SIMDMatrix() {
  62894. }
  62895. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  62896. var tm = this.m;
  62897. var om = other.m;
  62898. var m0 = SIMD.Float32x4.load(om, 0);
  62899. var m1 = SIMD.Float32x4.load(om, 4);
  62900. var m2 = SIMD.Float32x4.load(om, 8);
  62901. var m3 = SIMD.Float32x4.load(om, 12);
  62902. for (var i = 0; i < 16; i += 4) {
  62903. 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)))));
  62904. }
  62905. return this;
  62906. };
  62907. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  62908. var src = this.m;
  62909. var dest = other.m;
  62910. // Load the 4 rows
  62911. var src0 = SIMD.Float32x4.load(src, 0);
  62912. var src1 = SIMD.Float32x4.load(src, 4);
  62913. var src2 = SIMD.Float32x4.load(src, 8);
  62914. var src3 = SIMD.Float32x4.load(src, 12);
  62915. // Transpose the source matrix. Sort of. Not a true transpose operation
  62916. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  62917. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  62918. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  62919. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  62920. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  62921. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  62922. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  62923. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  62924. // This is a true transposition, but it will lead to an incorrect result
  62925. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  62926. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  62927. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  62928. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  62929. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  62930. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  62931. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  62932. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  62933. // ----
  62934. tmp1 = SIMD.Float32x4.mul(row2, row3);
  62935. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62936. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  62937. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  62938. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62939. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  62940. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  62941. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  62942. // ----
  62943. tmp1 = SIMD.Float32x4.mul(row1, row2);
  62944. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62945. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  62946. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  62947. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62948. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  62949. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  62950. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  62951. // ----
  62952. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  62953. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62954. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  62955. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  62956. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  62957. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62958. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  62959. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  62960. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  62961. // ----
  62962. tmp1 = SIMD.Float32x4.mul(row0, row1);
  62963. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62964. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  62965. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  62966. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62967. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  62968. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  62969. // ----
  62970. tmp1 = SIMD.Float32x4.mul(row0, row3);
  62971. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62972. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  62973. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  62974. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62975. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  62976. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  62977. // ----
  62978. tmp1 = SIMD.Float32x4.mul(row0, row2);
  62979. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62980. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  62981. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  62982. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62983. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  62984. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  62985. // Compute determinant
  62986. var det = SIMD.Float32x4.mul(row0, minor0);
  62987. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  62988. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  62989. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  62990. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  62991. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  62992. // These shuffles aren't necessary if the faulty transposition is done
  62993. // up at the top of this function.
  62994. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  62995. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  62996. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  62997. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  62998. // Compute final values by multiplying with 1/det
  62999. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  63000. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  63001. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  63002. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  63003. return this;
  63004. };
  63005. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  63006. var out = result.m;
  63007. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  63008. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  63009. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  63010. // cc.kmVec3Subtract(f, pCenter, pEye);
  63011. var f = SIMD.Float32x4.sub(center, eye);
  63012. // cc.kmVec3Normalize(f, f);
  63013. var tmp = SIMD.Float32x4.mul(f, f);
  63014. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63015. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63016. // cc.kmVec3Assign(up, pUp);
  63017. // cc.kmVec3Normalize(up, up);
  63018. tmp = SIMD.Float32x4.mul(up, up);
  63019. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63020. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63021. // cc.kmVec3Cross(s, f, up);
  63022. 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)));
  63023. // cc.kmVec3Normalize(s, s);
  63024. tmp = SIMD.Float32x4.mul(s, s);
  63025. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63026. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63027. // cc.kmVec3Cross(u, s, f);
  63028. 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)));
  63029. // cc.kmVec3Normalize(s, s);
  63030. tmp = SIMD.Float32x4.mul(s, s);
  63031. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63032. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63033. var zero = SIMD.Float32x4.splat(0.0);
  63034. s = SIMD.Float32x4.neg(s);
  63035. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  63036. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  63037. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  63038. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  63039. 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);
  63040. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  63041. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  63042. 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)))));
  63043. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  63044. 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)))));
  63045. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  63046. 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)))));
  63047. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  63048. 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)))));
  63049. };
  63050. return SIMDMatrix;
  63051. }());
  63052. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  63053. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  63054. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  63055. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  63056. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  63057. var SIMDHelper = (function () {
  63058. function SIMDHelper() {
  63059. }
  63060. Object.defineProperty(SIMDHelper, "IsEnabled", {
  63061. get: function () {
  63062. return SIMDHelper._isEnabled;
  63063. },
  63064. enumerable: true,
  63065. configurable: true
  63066. });
  63067. SIMDHelper.DisableSIMD = function () {
  63068. // Replace functions
  63069. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  63070. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  63071. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  63072. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  63073. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  63074. SIMDHelper._isEnabled = false;
  63075. };
  63076. SIMDHelper.EnableSIMD = function () {
  63077. if (self.SIMD === undefined) {
  63078. return;
  63079. }
  63080. // check if polyfills needed
  63081. if (!self.Math.fround) {
  63082. self.Math.fround = (function (array) { return function (x) {
  63083. return array[0] = x, array[0];
  63084. }; })(new Float32Array(1));
  63085. }
  63086. if (!self.Math.imul) {
  63087. self.Math.imul = function (a, b) {
  63088. var ah = (a >>> 16) & 0xffff;
  63089. var al = a & 0xffff;
  63090. var bh = (b >>> 16) & 0xffff;
  63091. var bl = b & 0xffff;
  63092. // the shift by 0 fixes the sign on the high part
  63093. // the final |0 converts the unsigned value into a signed value
  63094. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  63095. };
  63096. }
  63097. // Replace functions
  63098. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  63099. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  63100. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  63101. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  63102. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  63103. SIMDHelper._isEnabled = true;
  63104. };
  63105. return SIMDHelper;
  63106. }());
  63107. SIMDHelper._isEnabled = false;
  63108. BABYLON.SIMDHelper = SIMDHelper;
  63109. })(BABYLON || (BABYLON = {}));
  63110. //# sourceMappingURL=babylon.math.SIMD.js.map
  63111. var BABYLON;
  63112. (function (BABYLON) {
  63113. var VRDistortionCorrectionPostProcess = (function (_super) {
  63114. __extends(VRDistortionCorrectionPostProcess, _super);
  63115. //ANY
  63116. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  63117. var _this = _super.call(this, name, "vrDistortionCorrection", [
  63118. 'LensCenter',
  63119. 'Scale',
  63120. 'ScaleIn',
  63121. 'HmdWarpParam'
  63122. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  63123. _this._isRightEye = isRightEye;
  63124. _this._distortionFactors = vrMetrics.distortionK;
  63125. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  63126. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  63127. _this.onSizeChangedObservable.add(function () {
  63128. _this.aspectRatio = _this.width * .5 / _this.height;
  63129. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  63130. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  63131. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  63132. });
  63133. _this.onApplyObservable.add(function (effect) {
  63134. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  63135. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  63136. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  63137. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  63138. });
  63139. return _this;
  63140. }
  63141. return VRDistortionCorrectionPostProcess;
  63142. }(BABYLON.PostProcess));
  63143. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  63144. })(BABYLON || (BABYLON = {}));
  63145. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  63146. var BABYLON;
  63147. (function (BABYLON) {
  63148. var AnaglyphPostProcess = (function (_super) {
  63149. __extends(AnaglyphPostProcess, _super);
  63150. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  63151. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  63152. _this._passedProcess = rigCameras[0]._rigPostProcess;
  63153. _this.onApplyObservable.add(function (effect) {
  63154. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  63155. });
  63156. return _this;
  63157. }
  63158. return AnaglyphPostProcess;
  63159. }(BABYLON.PostProcess));
  63160. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  63161. })(BABYLON || (BABYLON = {}));
  63162. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  63163. var BABYLON;
  63164. (function (BABYLON) {
  63165. var StereoscopicInterlacePostProcess = (function (_super) {
  63166. __extends(StereoscopicInterlacePostProcess, _super);
  63167. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  63168. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  63169. _this._passedProcess = rigCameras[0]._rigPostProcess;
  63170. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  63171. _this.onSizeChangedObservable.add(function () {
  63172. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  63173. });
  63174. _this.onApplyObservable.add(function (effect) {
  63175. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  63176. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  63177. });
  63178. return _this;
  63179. }
  63180. return StereoscopicInterlacePostProcess;
  63181. }(BABYLON.PostProcess));
  63182. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  63183. })(BABYLON || (BABYLON = {}));
  63184. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  63185. var BABYLON;
  63186. (function (BABYLON) {
  63187. var FreeCameraDeviceOrientationInput = (function () {
  63188. function FreeCameraDeviceOrientationInput() {
  63189. var _this = this;
  63190. this._screenOrientationAngle = 0;
  63191. this._screenQuaternion = new BABYLON.Quaternion();
  63192. this._alpha = 0;
  63193. this._beta = 0;
  63194. this._gamma = 0;
  63195. this._orientationChanged = function () {
  63196. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  63197. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  63198. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  63199. };
  63200. this._deviceOrientation = function (evt) {
  63201. _this._alpha = evt.alpha;
  63202. _this._beta = evt.beta;
  63203. _this._gamma = evt.gamma;
  63204. };
  63205. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  63206. this._orientationChanged();
  63207. }
  63208. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  63209. get: function () {
  63210. return this._camera;
  63211. },
  63212. set: function (camera) {
  63213. this._camera = camera;
  63214. if (!this._camera.rotationQuaternion)
  63215. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  63216. },
  63217. enumerable: true,
  63218. configurable: true
  63219. });
  63220. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  63221. window.addEventListener("orientationchange", this._orientationChanged);
  63222. window.addEventListener("deviceorientation", this._deviceOrientation);
  63223. //In certain cases, the attach control is called AFTER orientation was changed,
  63224. //So this is needed.
  63225. this._orientationChanged();
  63226. };
  63227. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  63228. window.removeEventListener("orientationchange", this._orientationChanged);
  63229. window.removeEventListener("deviceorientation", this._deviceOrientation);
  63230. };
  63231. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  63232. //if no device orientation provided, don't update the rotation.
  63233. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  63234. if (!this._alpha)
  63235. return;
  63236. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  63237. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  63238. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  63239. //Mirror on XY Plane
  63240. this._camera.rotationQuaternion.z *= -1;
  63241. this._camera.rotationQuaternion.w *= -1;
  63242. };
  63243. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  63244. return "FreeCameraDeviceOrientationInput";
  63245. };
  63246. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  63247. return "deviceOrientation";
  63248. };
  63249. return FreeCameraDeviceOrientationInput;
  63250. }());
  63251. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  63252. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  63253. })(BABYLON || (BABYLON = {}));
  63254. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  63255. var BABYLON;
  63256. (function (BABYLON) {
  63257. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  63258. function ArcRotateCameraVRDeviceOrientationInput() {
  63259. this.alphaCorrection = 1;
  63260. this.betaCorrection = 1;
  63261. this.gammaCorrection = 1;
  63262. this._alpha = 0;
  63263. this._beta = 0;
  63264. this._gamma = 0;
  63265. this._dirty = false;
  63266. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  63267. }
  63268. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  63269. this.camera.attachControl(element, noPreventDefault);
  63270. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  63271. };
  63272. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  63273. var camera = this.camera;
  63274. this._alpha = +evt.alpha | 0;
  63275. this._beta = +evt.beta | 0;
  63276. this._gamma = +evt.gamma | 0;
  63277. this._dirty = true;
  63278. };
  63279. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  63280. if (this._dirty) {
  63281. this._dirty = false;
  63282. if (this._gamma < 0) {
  63283. this._gamma = 180 + this._gamma;
  63284. }
  63285. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  63286. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  63287. }
  63288. };
  63289. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  63290. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  63291. };
  63292. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  63293. return "ArcRotateCameraVRDeviceOrientationInput";
  63294. };
  63295. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  63296. return "VRDeviceOrientation";
  63297. };
  63298. return ArcRotateCameraVRDeviceOrientationInput;
  63299. }());
  63300. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  63301. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  63302. })(BABYLON || (BABYLON = {}));
  63303. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  63304. var BABYLON;
  63305. (function (BABYLON) {
  63306. var VRCameraMetrics = (function () {
  63307. function VRCameraMetrics() {
  63308. this.compensateDistortion = true;
  63309. }
  63310. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  63311. get: function () {
  63312. return this.hResolution / (2 * this.vResolution);
  63313. },
  63314. enumerable: true,
  63315. configurable: true
  63316. });
  63317. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  63318. get: function () {
  63319. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  63320. },
  63321. enumerable: true,
  63322. configurable: true
  63323. });
  63324. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  63325. get: function () {
  63326. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  63327. var h = (4 * meters) / this.hScreenSize;
  63328. return BABYLON.Matrix.Translation(h, 0, 0);
  63329. },
  63330. enumerable: true,
  63331. configurable: true
  63332. });
  63333. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  63334. get: function () {
  63335. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  63336. var h = (4 * meters) / this.hScreenSize;
  63337. return BABYLON.Matrix.Translation(-h, 0, 0);
  63338. },
  63339. enumerable: true,
  63340. configurable: true
  63341. });
  63342. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  63343. get: function () {
  63344. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  63345. },
  63346. enumerable: true,
  63347. configurable: true
  63348. });
  63349. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  63350. get: function () {
  63351. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  63352. },
  63353. enumerable: true,
  63354. configurable: true
  63355. });
  63356. VRCameraMetrics.GetDefault = function () {
  63357. var result = new VRCameraMetrics();
  63358. result.hResolution = 1280;
  63359. result.vResolution = 800;
  63360. result.hScreenSize = 0.149759993;
  63361. result.vScreenSize = 0.0935999975;
  63362. result.vScreenCenter = 0.0467999987;
  63363. result.eyeToScreenDistance = 0.0410000011;
  63364. result.lensSeparationDistance = 0.0635000020;
  63365. result.interpupillaryDistance = 0.0640000030;
  63366. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  63367. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  63368. result.postProcessScaleFactor = 1.714605507808412;
  63369. result.lensCenterOffset = 0.151976421;
  63370. return result;
  63371. };
  63372. return VRCameraMetrics;
  63373. }());
  63374. BABYLON.VRCameraMetrics = VRCameraMetrics;
  63375. })(BABYLON || (BABYLON = {}));
  63376. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  63377. var BABYLON;
  63378. (function (BABYLON) {
  63379. var WebVRFreeCamera = (function (_super) {
  63380. __extends(WebVRFreeCamera, _super);
  63381. function WebVRFreeCamera(name, position, scene, webVROptions) {
  63382. if (webVROptions === void 0) { webVROptions = {}; }
  63383. var _this = _super.call(this, name, position, scene) || this;
  63384. _this.webVROptions = webVROptions;
  63385. _this._vrDevice = null;
  63386. _this.rawPose = null;
  63387. _this._vrEnabled = false;
  63388. _this._specsVersion = 1.1;
  63389. _this._attached = false;
  63390. _this._positionOffset = BABYLON.Vector3.Zero();
  63391. _this._descendants = [];
  63392. _this.devicePosition = BABYLON.Vector3.Zero();
  63393. _this.deviceScaleFactor = 1;
  63394. _this.controllers = [];
  63395. _this.nonVRControllers = [];
  63396. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  63397. //legacy support - the compensation boolean was removed.
  63398. if (arguments.length === 5) {
  63399. _this.webVROptions = arguments[4];
  63400. }
  63401. // default webVR options
  63402. if (_this.webVROptions.trackPosition == undefined) {
  63403. _this.webVROptions.trackPosition = true;
  63404. }
  63405. if (_this.webVROptions.controllerMeshes == undefined) {
  63406. _this.webVROptions.controllerMeshes = true;
  63407. }
  63408. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  63409. _this.webVROptions.defaultLightningOnControllers = true;
  63410. }
  63411. _this.rotationQuaternion = new BABYLON.Quaternion();
  63412. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63413. if (_this.webVROptions && _this.webVROptions.positionScale) {
  63414. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  63415. }
  63416. //enable VR
  63417. _this.getEngine().initWebVR();
  63418. //check specs version
  63419. if (!window.VRFrameData) {
  63420. _this._specsVersion = 1.0;
  63421. _this._frameData = {};
  63422. }
  63423. else {
  63424. _this._frameData = new VRFrameData();
  63425. }
  63426. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  63427. if (!device) {
  63428. return;
  63429. }
  63430. _this._vrEnabled = true;
  63431. _this._vrDevice = device;
  63432. //reset the rig parameters.
  63433. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  63434. if (_this._attached) {
  63435. _this.getEngine().enableVR(_this._vrDevice);
  63436. }
  63437. });
  63438. // try to attach the controllers, if found.
  63439. _this.initControllers();
  63440. /**
  63441. * The idea behind the following lines:
  63442. * objects that have the camera as parent should actually have the rig cameras as a parent.
  63443. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  63444. * the second will not show it correctly.
  63445. *
  63446. * To solve this - each object that has the camera as parent will be added to a protected array.
  63447. * When the rig camera renders, it will take this array and set all of those to be its children.
  63448. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  63449. * Amazing!
  63450. */
  63451. scene.onBeforeCameraRenderObservable.add(function (camera) {
  63452. if (camera.parent === _this && _this.rigParenting) {
  63453. _this._descendants = _this.getDescendants(true, function (n) {
  63454. // don't take the cameras or the controllers!
  63455. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  63456. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  63457. return !isController && !isRigCamera;
  63458. });
  63459. _this._descendants.forEach(function (node) {
  63460. node.parent = camera;
  63461. });
  63462. }
  63463. });
  63464. scene.onAfterCameraRenderObservable.add(function (camera) {
  63465. if (camera.parent === _this && _this.rigParenting) {
  63466. _this._descendants.forEach(function (node) {
  63467. node.parent = _this;
  63468. });
  63469. }
  63470. });
  63471. return _this;
  63472. }
  63473. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  63474. set: function (callback) {
  63475. this._onControllersAttached = callback;
  63476. // after setting - if the controllers are already set, execute the callback.
  63477. if (this.controllers.length >= 2) {
  63478. callback(this.controllers);
  63479. }
  63480. },
  63481. enumerable: true,
  63482. configurable: true
  63483. });
  63484. Object.defineProperty(WebVRFreeCamera.prototype, "onNonVRControllerAttached", {
  63485. set: function (callback) {
  63486. this._onNonVRControllerAttached = callback;
  63487. this.nonVRControllers.forEach(function (controller) {
  63488. callback(controller);
  63489. });
  63490. },
  63491. enumerable: true,
  63492. configurable: true
  63493. });
  63494. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  63495. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  63496. var gp = _a[_i];
  63497. if (gp.hand === name) {
  63498. return gp;
  63499. }
  63500. }
  63501. return undefined;
  63502. };
  63503. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  63504. get: function () {
  63505. if (!this._leftController) {
  63506. this._leftController = this.getControllerByName("left");
  63507. }
  63508. return this._leftController;
  63509. },
  63510. enumerable: true,
  63511. configurable: true
  63512. });
  63513. ;
  63514. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  63515. get: function () {
  63516. if (!this._rightController) {
  63517. this._rightController = this.getControllerByName("right");
  63518. }
  63519. return this._rightController;
  63520. },
  63521. enumerable: true,
  63522. configurable: true
  63523. });
  63524. ;
  63525. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  63526. if (length === void 0) { length = 100; }
  63527. if (this.leftCamera) {
  63528. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  63529. }
  63530. else {
  63531. return _super.prototype.getForwardRay.call(this, length);
  63532. }
  63533. };
  63534. WebVRFreeCamera.prototype._checkInputs = function () {
  63535. if (this._vrEnabled) {
  63536. if (this._specsVersion === 1.1) {
  63537. this._vrDevice.getFrameData(this._frameData);
  63538. }
  63539. else {
  63540. //backwards comp
  63541. var pose = this._vrDevice.getPose();
  63542. this._frameData.pose = pose;
  63543. // calculate view and projection matrix
  63544. }
  63545. this.updateFromDevice(this._frameData.pose);
  63546. }
  63547. _super.prototype._checkInputs.call(this);
  63548. };
  63549. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  63550. if (poseData && poseData.orientation) {
  63551. this.rawPose = poseData;
  63552. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  63553. if (this.getScene().useRightHandedSystem) {
  63554. this.deviceRotationQuaternion.z *= -1;
  63555. this.deviceRotationQuaternion.w *= -1;
  63556. }
  63557. if (this.webVROptions.trackPosition && this.rawPose.position) {
  63558. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  63559. if (this.getScene().useRightHandedSystem) {
  63560. this.devicePosition.z *= -1;
  63561. }
  63562. }
  63563. }
  63564. };
  63565. /**
  63566. * WebVR's attach control will start broadcasting frames to the device.
  63567. * Note that in certain browsers (chrome for example) this function must be called
  63568. * within a user-interaction callback. Example:
  63569. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  63570. *
  63571. * @param {HTMLElement} element
  63572. * @param {boolean} [noPreventDefault]
  63573. *
  63574. * @memberOf WebVRFreeCamera
  63575. */
  63576. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  63577. _super.prototype.attachControl.call(this, element, noPreventDefault);
  63578. this._attached = true;
  63579. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  63580. if (this._vrEnabled) {
  63581. this.getEngine().enableVR(this._vrDevice);
  63582. }
  63583. };
  63584. WebVRFreeCamera.prototype.detachControl = function (element) {
  63585. _super.prototype.detachControl.call(this, element);
  63586. this._vrEnabled = false;
  63587. this._attached = false;
  63588. this.getEngine().disableVR();
  63589. };
  63590. WebVRFreeCamera.prototype.getClassName = function () {
  63591. return "WebVRFreeCamera";
  63592. };
  63593. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  63594. //uses the vrDisplay's "resetPose()".
  63595. //pitch and roll won't be affected.
  63596. this._vrDevice.resetPose();
  63597. };
  63598. WebVRFreeCamera.prototype._updateRigCameras = function () {
  63599. var camLeft = this._rigCameras[0];
  63600. var camRight = this._rigCameras[1];
  63601. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63602. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63603. camLeft.position.copyFrom(this.devicePosition);
  63604. camRight.position.copyFrom(this.devicePosition);
  63605. };
  63606. /**
  63607. * This function is called by the two RIG cameras.
  63608. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  63609. */
  63610. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  63611. var _this = this;
  63612. //WebVR 1.0
  63613. if (this._cameraRigParams["specs"] === 1.0) {
  63614. this._updateCameraRotationMatrix();
  63615. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  63616. // Computing target and final matrix
  63617. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  63618. if (this.getScene().useRightHandedSystem) {
  63619. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  63620. }
  63621. else {
  63622. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  63623. }
  63624. //now move the eye in the right direction
  63625. var eyeParams = this._cameraRigParams["eyeParameters"];
  63626. var offset = eyeParams.offset;
  63627. // it will actually always be 0, but just in case
  63628. if (this.getScene().useRightHandedSystem) {
  63629. offset[2] *= -1;
  63630. }
  63631. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  63632. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  63633. }
  63634. else {
  63635. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  63636. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  63637. if (!this.getScene().useRightHandedSystem) {
  63638. [2, 6, 8, 9, 14].forEach(function (num) {
  63639. _this._webvrViewMatrix.m[num] *= -1;
  63640. });
  63641. }
  63642. // update the camera rotation matrix
  63643. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  63644. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  63645. // Computing target and final matrix
  63646. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  63647. }
  63648. var parentCamera = this._cameraRigParams["parentCamera"];
  63649. // should the view matrix be updated with scale and position offset?
  63650. if (parentCamera.deviceScaleFactor !== 1) {
  63651. this._webvrViewMatrix.invert();
  63652. // scale the position, if set
  63653. if (parentCamera.deviceScaleFactor) {
  63654. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  63655. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  63656. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  63657. }
  63658. this._webvrViewMatrix.invert();
  63659. }
  63660. return this._webvrViewMatrix;
  63661. };
  63662. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  63663. var _this = this;
  63664. if (this._cameraRigParams["specs"] === 1.0) {
  63665. var eyeParams = this._cameraRigParams["eyeParameters"];
  63666. // deprecated!!
  63667. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  63668. }
  63669. else {
  63670. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  63671. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  63672. //babylon compatible matrix
  63673. if (!this.getScene().useRightHandedSystem) {
  63674. [8, 9, 10, 11].forEach(function (num) {
  63675. _this._projectionMatrix.m[num] *= -1;
  63676. });
  63677. }
  63678. }
  63679. return this._projectionMatrix;
  63680. };
  63681. WebVRFreeCamera.prototype.initControllers = function () {
  63682. var _this = this;
  63683. this.controllers = [];
  63684. new BABYLON.Gamepads(function (gp) {
  63685. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  63686. var webVrController = gp;
  63687. if (_this.webVROptions.controllerMeshes) {
  63688. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  63689. if (_this.webVROptions.defaultLightningOnControllers) {
  63690. if (!_this._lightOnControllers) {
  63691. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  63692. }
  63693. loadedMesh.getChildren().forEach(function (mesh) {
  63694. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  63695. });
  63696. }
  63697. });
  63698. }
  63699. webVrController.attachToPoseControlledCamera(_this);
  63700. // since this is async - sanity check. Is the controller already stored?
  63701. if (_this.controllers.indexOf(webVrController) === -1) {
  63702. //add to the controllers array
  63703. _this.controllers.push(webVrController);
  63704. //did we find enough controllers? Great! let the developer know.
  63705. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  63706. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  63707. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  63708. // So we're overriding setting left & right manually to be sure
  63709. var firstViveWandDetected = false;
  63710. for (var i = 0; i < _this.controllers.length; i++) {
  63711. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  63712. if (!firstViveWandDetected) {
  63713. firstViveWandDetected = true;
  63714. _this.controllers[i].hand = "left";
  63715. }
  63716. else {
  63717. _this.controllers[i].hand = "right";
  63718. }
  63719. }
  63720. }
  63721. _this._onControllersAttached(_this.controllers);
  63722. }
  63723. }
  63724. }
  63725. else {
  63726. _this.nonVRControllers.push(gp);
  63727. if (_this._onNonVRControllerAttached) {
  63728. _this._onNonVRControllerAttached(gp);
  63729. }
  63730. }
  63731. });
  63732. };
  63733. return WebVRFreeCamera;
  63734. }(BABYLON.FreeCamera));
  63735. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  63736. })(BABYLON || (BABYLON = {}));
  63737. //# sourceMappingURL=babylon.webVRCamera.js.map
  63738. /// <reference path="babylon.freeCamera.ts" />
  63739. var BABYLON;
  63740. (function (BABYLON) {
  63741. // We're mainly based on the logic defined into the FreeCamera code
  63742. var DeviceOrientationCamera = (function (_super) {
  63743. __extends(DeviceOrientationCamera, _super);
  63744. function DeviceOrientationCamera(name, position, scene) {
  63745. var _this = _super.call(this, name, position, scene) || this;
  63746. _this._quaternionCache = new BABYLON.Quaternion();
  63747. _this.inputs.addDeviceOrientation();
  63748. return _this;
  63749. }
  63750. DeviceOrientationCamera.prototype.getClassName = function () {
  63751. return "DeviceOrientationCamera";
  63752. };
  63753. DeviceOrientationCamera.prototype._checkInputs = function () {
  63754. _super.prototype._checkInputs.call(this);
  63755. this._quaternionCache.copyFrom(this.rotationQuaternion);
  63756. if (this._initialQuaternion) {
  63757. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  63758. }
  63759. };
  63760. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  63761. var _this = this;
  63762. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  63763. //can only work if this camera has a rotation quaternion already.
  63764. if (!this.rotationQuaternion)
  63765. return;
  63766. if (!this._initialQuaternion) {
  63767. this._initialQuaternion = new BABYLON.Quaternion();
  63768. }
  63769. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  63770. ['x', 'y', 'z'].forEach(function (axisName) {
  63771. if (!axis[axisName]) {
  63772. _this._initialQuaternion[axisName] = 0;
  63773. }
  63774. else {
  63775. _this._initialQuaternion[axisName] *= -1;
  63776. }
  63777. });
  63778. this._initialQuaternion.normalize();
  63779. //force rotation update
  63780. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  63781. };
  63782. return DeviceOrientationCamera;
  63783. }(BABYLON.FreeCamera));
  63784. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  63785. })(BABYLON || (BABYLON = {}));
  63786. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  63787. var BABYLON;
  63788. (function (BABYLON) {
  63789. var VRDeviceOrientationFreeCamera = (function (_super) {
  63790. __extends(VRDeviceOrientationFreeCamera, _super);
  63791. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  63792. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63793. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63794. var _this = _super.call(this, name, position, scene) || this;
  63795. vrCameraMetrics.compensateDistortion = compensateDistortion;
  63796. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  63797. return _this;
  63798. }
  63799. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  63800. return "VRDeviceOrientationFreeCamera";
  63801. };
  63802. return VRDeviceOrientationFreeCamera;
  63803. }(BABYLON.DeviceOrientationCamera));
  63804. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  63805. var VRDeviceOrientationGamepadCamera = (function (_super) {
  63806. __extends(VRDeviceOrientationGamepadCamera, _super);
  63807. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  63808. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63809. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63810. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  63811. _this.inputs.addGamepad();
  63812. return _this;
  63813. }
  63814. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  63815. return "VRDeviceOrientationGamepadCamera";
  63816. };
  63817. return VRDeviceOrientationGamepadCamera;
  63818. }(VRDeviceOrientationFreeCamera));
  63819. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  63820. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  63821. __extends(VRDeviceOrientationArcRotateCamera, _super);
  63822. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  63823. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63824. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63825. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63826. vrCameraMetrics.compensateDistortion = compensateDistortion;
  63827. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  63828. _this.inputs.addVRDeviceOrientation();
  63829. return _this;
  63830. }
  63831. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  63832. return "VRDeviceOrientationArcRotateCamera";
  63833. };
  63834. return VRDeviceOrientationArcRotateCamera;
  63835. }(BABYLON.ArcRotateCamera));
  63836. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  63837. })(BABYLON || (BABYLON = {}));
  63838. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  63839. /// <reference path="babylon.freeCamera.ts" />
  63840. /// <reference path="babylon.arcRotateCamera.ts" />
  63841. /// <reference path="babylon.gamepadCamera.ts" />
  63842. /// <reference path="babylon.universalCamera.ts" />
  63843. var BABYLON;
  63844. (function (BABYLON) {
  63845. var AnaglyphFreeCamera = (function (_super) {
  63846. __extends(AnaglyphFreeCamera, _super);
  63847. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  63848. var _this = _super.call(this, name, position, scene) || this;
  63849. _this.interaxialDistance = interaxialDistance;
  63850. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63851. return _this;
  63852. }
  63853. AnaglyphFreeCamera.prototype.getClassName = function () {
  63854. return "AnaglyphFreeCamera";
  63855. };
  63856. return AnaglyphFreeCamera;
  63857. }(BABYLON.FreeCamera));
  63858. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  63859. var AnaglyphArcRotateCamera = (function (_super) {
  63860. __extends(AnaglyphArcRotateCamera, _super);
  63861. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  63862. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63863. _this.interaxialDistance = interaxialDistance;
  63864. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63865. return _this;
  63866. }
  63867. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  63868. return "AnaglyphArcRotateCamera";
  63869. };
  63870. return AnaglyphArcRotateCamera;
  63871. }(BABYLON.ArcRotateCamera));
  63872. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  63873. var AnaglyphGamepadCamera = (function (_super) {
  63874. __extends(AnaglyphGamepadCamera, _super);
  63875. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  63876. var _this = _super.call(this, name, position, scene) || this;
  63877. _this.interaxialDistance = interaxialDistance;
  63878. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63879. return _this;
  63880. }
  63881. AnaglyphGamepadCamera.prototype.getClassName = function () {
  63882. return "AnaglyphGamepadCamera";
  63883. };
  63884. return AnaglyphGamepadCamera;
  63885. }(BABYLON.GamepadCamera));
  63886. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  63887. var AnaglyphUniversalCamera = (function (_super) {
  63888. __extends(AnaglyphUniversalCamera, _super);
  63889. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  63890. var _this = _super.call(this, name, position, scene) || this;
  63891. _this.interaxialDistance = interaxialDistance;
  63892. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63893. return _this;
  63894. }
  63895. AnaglyphUniversalCamera.prototype.getClassName = function () {
  63896. return "AnaglyphUniversalCamera";
  63897. };
  63898. return AnaglyphUniversalCamera;
  63899. }(BABYLON.UniversalCamera));
  63900. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  63901. var StereoscopicFreeCamera = (function (_super) {
  63902. __extends(StereoscopicFreeCamera, _super);
  63903. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63904. var _this = _super.call(this, name, position, scene) || this;
  63905. _this.interaxialDistance = interaxialDistance;
  63906. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63907. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63908. return _this;
  63909. }
  63910. StereoscopicFreeCamera.prototype.getClassName = function () {
  63911. return "StereoscopicFreeCamera";
  63912. };
  63913. return StereoscopicFreeCamera;
  63914. }(BABYLON.FreeCamera));
  63915. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  63916. var StereoscopicArcRotateCamera = (function (_super) {
  63917. __extends(StereoscopicArcRotateCamera, _super);
  63918. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  63919. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63920. _this.interaxialDistance = interaxialDistance;
  63921. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63922. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63923. return _this;
  63924. }
  63925. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  63926. return "StereoscopicArcRotateCamera";
  63927. };
  63928. return StereoscopicArcRotateCamera;
  63929. }(BABYLON.ArcRotateCamera));
  63930. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  63931. var StereoscopicGamepadCamera = (function (_super) {
  63932. __extends(StereoscopicGamepadCamera, _super);
  63933. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63934. var _this = _super.call(this, name, position, scene) || this;
  63935. _this.interaxialDistance = interaxialDistance;
  63936. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63937. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63938. return _this;
  63939. }
  63940. StereoscopicGamepadCamera.prototype.getClassName = function () {
  63941. return "StereoscopicGamepadCamera";
  63942. };
  63943. return StereoscopicGamepadCamera;
  63944. }(BABYLON.GamepadCamera));
  63945. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  63946. var StereoscopicUniversalCamera = (function (_super) {
  63947. __extends(StereoscopicUniversalCamera, _super);
  63948. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63949. var _this = _super.call(this, name, position, scene) || this;
  63950. _this.interaxialDistance = interaxialDistance;
  63951. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63952. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63953. return _this;
  63954. }
  63955. StereoscopicUniversalCamera.prototype.getClassName = function () {
  63956. return "StereoscopicUniversalCamera";
  63957. };
  63958. return StereoscopicUniversalCamera;
  63959. }(BABYLON.UniversalCamera));
  63960. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  63961. })(BABYLON || (BABYLON = {}));
  63962. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  63963. // Mainly based on these 2 articles :
  63964. // 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
  63965. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  63966. var BABYLON;
  63967. (function (BABYLON) {
  63968. var JoystickAxis;
  63969. (function (JoystickAxis) {
  63970. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  63971. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  63972. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  63973. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  63974. var VirtualJoystick = (function () {
  63975. function VirtualJoystick(leftJoystick) {
  63976. var _this = this;
  63977. if (leftJoystick) {
  63978. this._leftJoystick = true;
  63979. }
  63980. else {
  63981. this._leftJoystick = false;
  63982. }
  63983. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  63984. VirtualJoystick._globalJoystickIndex++;
  63985. // By default left & right arrow keys are moving the X
  63986. // and up & down keys are moving the Y
  63987. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  63988. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  63989. this.reverseLeftRight = false;
  63990. this.reverseUpDown = false;
  63991. // collections of pointers
  63992. this._touches = new BABYLON.StringDictionary();
  63993. this.deltaPosition = BABYLON.Vector3.Zero();
  63994. this._joystickSensibility = 25;
  63995. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  63996. this._rotationSpeed = 25;
  63997. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  63998. this._rotateOnAxisRelativeToMesh = false;
  63999. this._onResize = function (evt) {
  64000. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  64001. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  64002. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  64003. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  64004. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  64005. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  64006. };
  64007. // injecting a canvas element on top of the canvas 3D game
  64008. if (!VirtualJoystick.vjCanvas) {
  64009. window.addEventListener("resize", this._onResize, false);
  64010. VirtualJoystick.vjCanvas = document.createElement("canvas");
  64011. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  64012. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  64013. VirtualJoystick.vjCanvas.width = window.innerWidth;
  64014. VirtualJoystick.vjCanvas.height = window.innerHeight;
  64015. VirtualJoystick.vjCanvas.style.width = "100%";
  64016. VirtualJoystick.vjCanvas.style.height = "100%";
  64017. VirtualJoystick.vjCanvas.style.position = "absolute";
  64018. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  64019. VirtualJoystick.vjCanvas.style.top = "0px";
  64020. VirtualJoystick.vjCanvas.style.left = "0px";
  64021. VirtualJoystick.vjCanvas.style.zIndex = "5";
  64022. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  64023. // Support for jQuery PEP polyfill
  64024. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  64025. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  64026. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  64027. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  64028. document.body.appendChild(VirtualJoystick.vjCanvas);
  64029. }
  64030. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  64031. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  64032. this.pressed = false;
  64033. // default joystick color
  64034. this._joystickColor = "cyan";
  64035. this._joystickPointerID = -1;
  64036. // current joystick position
  64037. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  64038. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  64039. // origin joystick position
  64040. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  64041. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  64042. this._onPointerDownHandlerRef = function (evt) {
  64043. _this._onPointerDown(evt);
  64044. };
  64045. this._onPointerMoveHandlerRef = function (evt) {
  64046. _this._onPointerMove(evt);
  64047. };
  64048. this._onPointerOutHandlerRef = function (evt) {
  64049. _this._onPointerUp(evt);
  64050. };
  64051. this._onPointerUpHandlerRef = function (evt) {
  64052. _this._onPointerUp(evt);
  64053. };
  64054. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  64055. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  64056. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  64057. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  64058. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  64059. evt.preventDefault(); // Disables system menu
  64060. }, false);
  64061. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  64062. }
  64063. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  64064. this._joystickSensibility = newJoystickSensibility;
  64065. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  64066. };
  64067. VirtualJoystick.prototype._onPointerDown = function (e) {
  64068. var positionOnScreenCondition;
  64069. e.preventDefault();
  64070. if (this._leftJoystick === true) {
  64071. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  64072. }
  64073. else {
  64074. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  64075. }
  64076. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  64077. // First contact will be dedicated to the virtual joystick
  64078. this._joystickPointerID = e.pointerId;
  64079. this._joystickPointerStartPos.x = e.clientX;
  64080. this._joystickPointerStartPos.y = e.clientY;
  64081. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  64082. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  64083. this._deltaJoystickVector.x = 0;
  64084. this._deltaJoystickVector.y = 0;
  64085. this.pressed = true;
  64086. this._touches.add(e.pointerId.toString(), e);
  64087. }
  64088. else {
  64089. // You can only trigger the action buttons with a joystick declared
  64090. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  64091. this._action();
  64092. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  64093. }
  64094. }
  64095. };
  64096. VirtualJoystick.prototype._onPointerMove = function (e) {
  64097. // If the current pointer is the one associated to the joystick (first touch contact)
  64098. if (this._joystickPointerID == e.pointerId) {
  64099. this._joystickPointerPos.x = e.clientX;
  64100. this._joystickPointerPos.y = e.clientY;
  64101. this._deltaJoystickVector = this._joystickPointerPos.clone();
  64102. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  64103. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  64104. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  64105. switch (this._axisTargetedByLeftAndRight) {
  64106. case JoystickAxis.X:
  64107. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  64108. break;
  64109. case JoystickAxis.Y:
  64110. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  64111. break;
  64112. case JoystickAxis.Z:
  64113. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  64114. break;
  64115. }
  64116. var directionUpDown = this.reverseUpDown ? 1 : -1;
  64117. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  64118. switch (this._axisTargetedByUpAndDown) {
  64119. case JoystickAxis.X:
  64120. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  64121. break;
  64122. case JoystickAxis.Y:
  64123. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  64124. break;
  64125. case JoystickAxis.Z:
  64126. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  64127. break;
  64128. }
  64129. }
  64130. else {
  64131. var data = this._touches.get(e.pointerId.toString());
  64132. if (data) {
  64133. data.x = e.clientX;
  64134. data.y = e.clientY;
  64135. }
  64136. }
  64137. };
  64138. VirtualJoystick.prototype._onPointerUp = function (e) {
  64139. if (this._joystickPointerID == e.pointerId) {
  64140. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  64141. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  64142. this._joystickPointerID = -1;
  64143. this.pressed = false;
  64144. }
  64145. else {
  64146. var touch = this._touches.get(e.pointerId.toString());
  64147. if (touch) {
  64148. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  64149. }
  64150. }
  64151. this._deltaJoystickVector.x = 0;
  64152. this._deltaJoystickVector.y = 0;
  64153. this._touches.remove(e.pointerId.toString());
  64154. };
  64155. /**
  64156. * Change the color of the virtual joystick
  64157. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  64158. */
  64159. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  64160. this._joystickColor = newColor;
  64161. };
  64162. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  64163. this._action = action;
  64164. };
  64165. // Define which axis you'd like to control for left & right
  64166. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  64167. switch (axis) {
  64168. case JoystickAxis.X:
  64169. case JoystickAxis.Y:
  64170. case JoystickAxis.Z:
  64171. this._axisTargetedByLeftAndRight = axis;
  64172. break;
  64173. default:
  64174. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  64175. break;
  64176. }
  64177. };
  64178. // Define which axis you'd like to control for up & down
  64179. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  64180. switch (axis) {
  64181. case JoystickAxis.X:
  64182. case JoystickAxis.Y:
  64183. case JoystickAxis.Z:
  64184. this._axisTargetedByUpAndDown = axis;
  64185. break;
  64186. default:
  64187. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  64188. break;
  64189. }
  64190. };
  64191. VirtualJoystick.prototype._clearCanvas = function () {
  64192. if (this._leftJoystick) {
  64193. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  64194. }
  64195. else {
  64196. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  64197. }
  64198. };
  64199. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  64200. var _this = this;
  64201. if (this.pressed) {
  64202. this._touches.forEach(function (key, touch) {
  64203. if (touch.pointerId === _this._joystickPointerID) {
  64204. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  64205. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  64206. VirtualJoystick.vjCanvasContext.beginPath();
  64207. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  64208. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64209. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  64210. VirtualJoystick.vjCanvasContext.stroke();
  64211. VirtualJoystick.vjCanvasContext.closePath();
  64212. VirtualJoystick.vjCanvasContext.beginPath();
  64213. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64214. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  64215. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  64216. VirtualJoystick.vjCanvasContext.stroke();
  64217. VirtualJoystick.vjCanvasContext.closePath();
  64218. VirtualJoystick.vjCanvasContext.beginPath();
  64219. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64220. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  64221. VirtualJoystick.vjCanvasContext.stroke();
  64222. VirtualJoystick.vjCanvasContext.closePath();
  64223. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  64224. }
  64225. else {
  64226. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  64227. VirtualJoystick.vjCanvasContext.beginPath();
  64228. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  64229. VirtualJoystick.vjCanvasContext.beginPath();
  64230. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  64231. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  64232. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  64233. VirtualJoystick.vjCanvasContext.stroke();
  64234. VirtualJoystick.vjCanvasContext.closePath();
  64235. touch.prevX = touch.x;
  64236. touch.prevY = touch.y;
  64237. }
  64238. ;
  64239. });
  64240. }
  64241. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  64242. };
  64243. VirtualJoystick.prototype.releaseCanvas = function () {
  64244. if (VirtualJoystick.vjCanvas) {
  64245. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  64246. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  64247. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  64248. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  64249. window.removeEventListener("resize", this._onResize);
  64250. document.body.removeChild(VirtualJoystick.vjCanvas);
  64251. VirtualJoystick.vjCanvas = null;
  64252. }
  64253. };
  64254. return VirtualJoystick;
  64255. }());
  64256. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  64257. VirtualJoystick._globalJoystickIndex = 0;
  64258. BABYLON.VirtualJoystick = VirtualJoystick;
  64259. })(BABYLON || (BABYLON = {}));
  64260. //# sourceMappingURL=babylon.virtualJoystick.js.map
  64261. var BABYLON;
  64262. (function (BABYLON) {
  64263. // We're mainly based on the logic defined into the FreeCamera code
  64264. var VirtualJoysticksCamera = (function (_super) {
  64265. __extends(VirtualJoysticksCamera, _super);
  64266. function VirtualJoysticksCamera(name, position, scene) {
  64267. var _this = _super.call(this, name, position, scene) || this;
  64268. _this.inputs.addVirtualJoystick();
  64269. return _this;
  64270. }
  64271. VirtualJoysticksCamera.prototype.getClassName = function () {
  64272. return "VirtualJoysticksCamera";
  64273. };
  64274. return VirtualJoysticksCamera;
  64275. }(BABYLON.FreeCamera));
  64276. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  64277. })(BABYLON || (BABYLON = {}));
  64278. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  64279. var BABYLON;
  64280. (function (BABYLON) {
  64281. var FreeCameraVirtualJoystickInput = (function () {
  64282. function FreeCameraVirtualJoystickInput() {
  64283. }
  64284. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  64285. return this._leftjoystick;
  64286. };
  64287. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  64288. return this._rightjoystick;
  64289. };
  64290. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  64291. if (this._leftjoystick) {
  64292. var camera = this.camera;
  64293. var speed = camera._computeLocalCameraSpeed() * 50;
  64294. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  64295. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  64296. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  64297. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  64298. if (!this._leftjoystick.pressed) {
  64299. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  64300. }
  64301. if (!this._rightjoystick.pressed) {
  64302. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  64303. }
  64304. }
  64305. };
  64306. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  64307. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  64308. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  64309. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  64310. this._leftjoystick.setJoystickSensibility(0.15);
  64311. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  64312. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  64313. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  64314. this._rightjoystick.reverseUpDown = true;
  64315. this._rightjoystick.setJoystickSensibility(0.05);
  64316. this._rightjoystick.setJoystickColor("yellow");
  64317. };
  64318. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  64319. this._leftjoystick.releaseCanvas();
  64320. this._rightjoystick.releaseCanvas();
  64321. };
  64322. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  64323. return "FreeCameraVirtualJoystickInput";
  64324. };
  64325. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  64326. return "virtualJoystick";
  64327. };
  64328. return FreeCameraVirtualJoystickInput;
  64329. }());
  64330. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  64331. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  64332. })(BABYLON || (BABYLON = {}));
  64333. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  64334. var BABYLON;
  64335. (function (BABYLON) {
  64336. var SimplificationSettings = (function () {
  64337. function SimplificationSettings(quality, distance, optimizeMesh) {
  64338. this.quality = quality;
  64339. this.distance = distance;
  64340. this.optimizeMesh = optimizeMesh;
  64341. }
  64342. return SimplificationSettings;
  64343. }());
  64344. BABYLON.SimplificationSettings = SimplificationSettings;
  64345. var SimplificationQueue = (function () {
  64346. function SimplificationQueue() {
  64347. this.running = false;
  64348. this._simplificationArray = [];
  64349. }
  64350. SimplificationQueue.prototype.addTask = function (task) {
  64351. this._simplificationArray.push(task);
  64352. };
  64353. SimplificationQueue.prototype.executeNext = function () {
  64354. var task = this._simplificationArray.pop();
  64355. if (task) {
  64356. this.running = true;
  64357. this.runSimplification(task);
  64358. }
  64359. else {
  64360. this.running = false;
  64361. }
  64362. };
  64363. SimplificationQueue.prototype.runSimplification = function (task) {
  64364. var _this = this;
  64365. if (task.parallelProcessing) {
  64366. //parallel simplifier
  64367. task.settings.forEach(function (setting) {
  64368. var simplifier = _this.getSimplifier(task);
  64369. simplifier.simplify(setting, function (newMesh) {
  64370. task.mesh.addLODLevel(setting.distance, newMesh);
  64371. newMesh.isVisible = true;
  64372. //check if it is the last
  64373. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  64374. //all done, run the success callback.
  64375. task.successCallback();
  64376. }
  64377. _this.executeNext();
  64378. });
  64379. });
  64380. }
  64381. else {
  64382. //single simplifier.
  64383. var simplifier = this.getSimplifier(task);
  64384. var runDecimation = function (setting, callback) {
  64385. simplifier.simplify(setting, function (newMesh) {
  64386. task.mesh.addLODLevel(setting.distance, newMesh);
  64387. newMesh.isVisible = true;
  64388. //run the next quality level
  64389. callback();
  64390. });
  64391. };
  64392. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  64393. runDecimation(task.settings[loop.index], function () {
  64394. loop.executeNext();
  64395. });
  64396. }, function () {
  64397. //execution ended, run the success callback.
  64398. if (task.successCallback) {
  64399. task.successCallback();
  64400. }
  64401. _this.executeNext();
  64402. });
  64403. }
  64404. };
  64405. SimplificationQueue.prototype.getSimplifier = function (task) {
  64406. switch (task.simplificationType) {
  64407. case SimplificationType.QUADRATIC:
  64408. default:
  64409. return new QuadraticErrorSimplification(task.mesh);
  64410. }
  64411. };
  64412. return SimplificationQueue;
  64413. }());
  64414. BABYLON.SimplificationQueue = SimplificationQueue;
  64415. /**
  64416. * The implemented types of simplification.
  64417. * At the moment only Quadratic Error Decimation is implemented.
  64418. */
  64419. var SimplificationType;
  64420. (function (SimplificationType) {
  64421. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  64422. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  64423. var DecimationTriangle = (function () {
  64424. function DecimationTriangle(vertices) {
  64425. this.vertices = vertices;
  64426. this.error = new Array(4);
  64427. this.deleted = false;
  64428. this.isDirty = false;
  64429. this.deletePending = false;
  64430. this.borderFactor = 0;
  64431. }
  64432. return DecimationTriangle;
  64433. }());
  64434. BABYLON.DecimationTriangle = DecimationTriangle;
  64435. var DecimationVertex = (function () {
  64436. function DecimationVertex(position, id) {
  64437. this.position = position;
  64438. this.id = id;
  64439. this.isBorder = true;
  64440. this.q = new QuadraticMatrix();
  64441. this.triangleCount = 0;
  64442. this.triangleStart = 0;
  64443. this.originalOffsets = [];
  64444. }
  64445. DecimationVertex.prototype.updatePosition = function (newPosition) {
  64446. this.position.copyFrom(newPosition);
  64447. };
  64448. return DecimationVertex;
  64449. }());
  64450. BABYLON.DecimationVertex = DecimationVertex;
  64451. var QuadraticMatrix = (function () {
  64452. function QuadraticMatrix(data) {
  64453. this.data = new Array(10);
  64454. for (var i = 0; i < 10; ++i) {
  64455. if (data && data[i]) {
  64456. this.data[i] = data[i];
  64457. }
  64458. else {
  64459. this.data[i] = 0;
  64460. }
  64461. }
  64462. }
  64463. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  64464. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  64465. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  64466. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  64467. return det;
  64468. };
  64469. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  64470. for (var i = 0; i < 10; ++i) {
  64471. this.data[i] += matrix.data[i];
  64472. }
  64473. };
  64474. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  64475. for (var i = 0; i < 10; ++i) {
  64476. this.data[i] += data[i];
  64477. }
  64478. };
  64479. QuadraticMatrix.prototype.add = function (matrix) {
  64480. var m = new QuadraticMatrix();
  64481. for (var i = 0; i < 10; ++i) {
  64482. m.data[i] = this.data[i] + matrix.data[i];
  64483. }
  64484. return m;
  64485. };
  64486. QuadraticMatrix.FromData = function (a, b, c, d) {
  64487. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  64488. };
  64489. //returning an array to avoid garbage collection
  64490. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  64491. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  64492. };
  64493. return QuadraticMatrix;
  64494. }());
  64495. BABYLON.QuadraticMatrix = QuadraticMatrix;
  64496. var Reference = (function () {
  64497. function Reference(vertexId, triangleId) {
  64498. this.vertexId = vertexId;
  64499. this.triangleId = triangleId;
  64500. }
  64501. return Reference;
  64502. }());
  64503. BABYLON.Reference = Reference;
  64504. /**
  64505. * An implementation of the Quadratic Error simplification algorithm.
  64506. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  64507. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  64508. * @author RaananW
  64509. */
  64510. var QuadraticErrorSimplification = (function () {
  64511. function QuadraticErrorSimplification(_mesh) {
  64512. this._mesh = _mesh;
  64513. this.initialized = false;
  64514. this.syncIterations = 5000;
  64515. this.aggressiveness = 7;
  64516. this.decimationIterations = 100;
  64517. this.boundingBoxEpsilon = BABYLON.Epsilon;
  64518. }
  64519. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  64520. var _this = this;
  64521. this.initDecimatedMesh();
  64522. //iterating through the submeshes array, one after the other.
  64523. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  64524. _this.initWithMesh(loop.index, function () {
  64525. _this.runDecimation(settings, loop.index, function () {
  64526. loop.executeNext();
  64527. });
  64528. }, settings.optimizeMesh);
  64529. }, function () {
  64530. setTimeout(function () {
  64531. successCallback(_this._reconstructedMesh);
  64532. }, 0);
  64533. });
  64534. };
  64535. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  64536. var _this = this;
  64537. var gCount = 0;
  64538. triangle.vertices.forEach(function (vertex) {
  64539. var count = 0;
  64540. var vPos = vertex.position;
  64541. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  64542. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  64543. ++count;
  64544. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  64545. ++count;
  64546. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  64547. ++count;
  64548. if (count > 1) {
  64549. ++gCount;
  64550. }
  64551. ;
  64552. });
  64553. if (gCount > 1) {
  64554. console.log(triangle, gCount);
  64555. }
  64556. return gCount > 1;
  64557. };
  64558. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  64559. var _this = this;
  64560. var targetCount = ~~(this.triangles.length * settings.quality);
  64561. var deletedTriangles = 0;
  64562. var triangleCount = this.triangles.length;
  64563. var iterationFunction = function (iteration, callback) {
  64564. setTimeout(function () {
  64565. if (iteration % 5 === 0) {
  64566. _this.updateMesh(iteration === 0);
  64567. }
  64568. for (var i = 0; i < _this.triangles.length; ++i) {
  64569. _this.triangles[i].isDirty = false;
  64570. }
  64571. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  64572. var trianglesIterator = function (i) {
  64573. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  64574. var t = _this.triangles[tIdx];
  64575. if (!t)
  64576. return;
  64577. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  64578. return;
  64579. }
  64580. for (var j = 0; j < 3; ++j) {
  64581. if (t.error[j] < threshold) {
  64582. var deleted0 = [];
  64583. var deleted1 = [];
  64584. var v0 = t.vertices[j];
  64585. var v1 = t.vertices[(j + 1) % 3];
  64586. if (v0.isBorder || v1.isBorder)
  64587. continue;
  64588. var p = BABYLON.Vector3.Zero();
  64589. var n = BABYLON.Vector3.Zero();
  64590. var uv = BABYLON.Vector2.Zero();
  64591. var color = new BABYLON.Color4(0, 0, 0, 1);
  64592. _this.calculateError(v0, v1, p, n, uv, color);
  64593. var delTr = [];
  64594. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  64595. continue;
  64596. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  64597. continue;
  64598. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  64599. continue;
  64600. var uniqueArray = [];
  64601. delTr.forEach(function (deletedT) {
  64602. if (uniqueArray.indexOf(deletedT) === -1) {
  64603. deletedT.deletePending = true;
  64604. uniqueArray.push(deletedT);
  64605. }
  64606. });
  64607. if (uniqueArray.length % 2 !== 0) {
  64608. continue;
  64609. }
  64610. v0.q = v1.q.add(v0.q);
  64611. v0.updatePosition(p);
  64612. var tStart = _this.references.length;
  64613. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  64614. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  64615. var tCount = _this.references.length - tStart;
  64616. if (tCount <= v0.triangleCount) {
  64617. if (tCount) {
  64618. for (var c = 0; c < tCount; c++) {
  64619. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  64620. }
  64621. }
  64622. }
  64623. else {
  64624. v0.triangleStart = tStart;
  64625. }
  64626. v0.triangleCount = tCount;
  64627. break;
  64628. }
  64629. }
  64630. };
  64631. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  64632. }, 0);
  64633. };
  64634. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  64635. if (triangleCount - deletedTriangles <= targetCount)
  64636. loop.breakLoop();
  64637. else {
  64638. iterationFunction(loop.index, function () {
  64639. loop.executeNext();
  64640. });
  64641. }
  64642. }, function () {
  64643. setTimeout(function () {
  64644. //reconstruct this part of the mesh
  64645. _this.reconstructMesh(submeshIndex);
  64646. successCallback();
  64647. }, 0);
  64648. });
  64649. };
  64650. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  64651. var _this = this;
  64652. this.vertices = [];
  64653. this.triangles = [];
  64654. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64655. var indices = this._mesh.getIndices();
  64656. var submesh = this._mesh.subMeshes[submeshIndex];
  64657. var findInVertices = function (positionToSearch) {
  64658. if (optimizeMesh) {
  64659. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  64660. if (_this.vertices[ii].position.equals(positionToSearch)) {
  64661. return _this.vertices[ii];
  64662. }
  64663. }
  64664. }
  64665. return null;
  64666. };
  64667. var vertexReferences = [];
  64668. var vertexInit = function (i) {
  64669. var offset = i + submesh.verticesStart;
  64670. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  64671. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  64672. vertex.originalOffsets.push(offset);
  64673. if (vertex.id === _this.vertices.length) {
  64674. _this.vertices.push(vertex);
  64675. }
  64676. vertexReferences.push(vertex.id);
  64677. };
  64678. //var totalVertices = mesh.getTotalVertices();
  64679. var totalVertices = submesh.verticesCount;
  64680. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  64681. var indicesInit = function (i) {
  64682. var offset = (submesh.indexStart / 3) + i;
  64683. var pos = (offset * 3);
  64684. var i0 = indices[pos + 0];
  64685. var i1 = indices[pos + 1];
  64686. var i2 = indices[pos + 2];
  64687. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  64688. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  64689. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  64690. var triangle = new DecimationTriangle([v0, v1, v2]);
  64691. triangle.originalOffset = pos;
  64692. _this.triangles.push(triangle);
  64693. };
  64694. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  64695. _this.init(callback);
  64696. });
  64697. });
  64698. };
  64699. QuadraticErrorSimplification.prototype.init = function (callback) {
  64700. var _this = this;
  64701. var triangleInit1 = function (i) {
  64702. var t = _this.triangles[i];
  64703. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  64704. for (var j = 0; j < 3; j++) {
  64705. 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))));
  64706. }
  64707. };
  64708. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  64709. var triangleInit2 = function (i) {
  64710. var t = _this.triangles[i];
  64711. for (var j = 0; j < 3; ++j) {
  64712. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  64713. }
  64714. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  64715. };
  64716. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  64717. _this.initialized = true;
  64718. callback();
  64719. });
  64720. });
  64721. };
  64722. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  64723. var newTriangles = [];
  64724. var i;
  64725. for (i = 0; i < this.vertices.length; ++i) {
  64726. this.vertices[i].triangleCount = 0;
  64727. }
  64728. var t;
  64729. var j;
  64730. for (i = 0; i < this.triangles.length; ++i) {
  64731. if (!this.triangles[i].deleted) {
  64732. t = this.triangles[i];
  64733. for (j = 0; j < 3; ++j) {
  64734. t.vertices[j].triangleCount = 1;
  64735. }
  64736. newTriangles.push(t);
  64737. }
  64738. }
  64739. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  64740. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  64741. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  64742. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  64743. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64744. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64745. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64746. var vertexCount = 0;
  64747. for (i = 0; i < this.vertices.length; ++i) {
  64748. var vertex = this.vertices[i];
  64749. vertex.id = vertexCount;
  64750. if (vertex.triangleCount) {
  64751. vertex.originalOffsets.forEach(function (originalOffset) {
  64752. newPositionData.push(vertex.position.x);
  64753. newPositionData.push(vertex.position.y);
  64754. newPositionData.push(vertex.position.z);
  64755. newNormalData.push(normalData[originalOffset * 3]);
  64756. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  64757. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  64758. if (uvs && uvs.length) {
  64759. newUVsData.push(uvs[(originalOffset * 2)]);
  64760. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  64761. }
  64762. else if (colorsData && colorsData.length) {
  64763. newColorsData.push(colorsData[(originalOffset * 4)]);
  64764. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  64765. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  64766. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  64767. }
  64768. ++vertexCount;
  64769. });
  64770. }
  64771. }
  64772. var startingIndex = this._reconstructedMesh.getTotalIndices();
  64773. var startingVertex = this._reconstructedMesh.getTotalVertices();
  64774. var submeshesArray = this._reconstructedMesh.subMeshes;
  64775. this._reconstructedMesh.subMeshes = [];
  64776. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  64777. var originalIndices = this._mesh.getIndices();
  64778. for (i = 0; i < newTriangles.length; ++i) {
  64779. t = newTriangles[i]; //now get the new referencing point for each vertex
  64780. [0, 1, 2].forEach(function (idx) {
  64781. var id = originalIndices[t.originalOffset + idx];
  64782. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  64783. if (offset < 0)
  64784. offset = 0;
  64785. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  64786. });
  64787. }
  64788. //overwriting the old vertex buffers and indices.
  64789. this._reconstructedMesh.setIndices(newIndicesArray);
  64790. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  64791. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  64792. if (newUVsData.length > 0)
  64793. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  64794. if (newColorsData.length > 0)
  64795. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  64796. //create submesh
  64797. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  64798. if (submeshIndex > 0) {
  64799. this._reconstructedMesh.subMeshes = [];
  64800. submeshesArray.forEach(function (submesh) {
  64801. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  64802. });
  64803. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  64804. }
  64805. };
  64806. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  64807. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  64808. this._reconstructedMesh.material = this._mesh.material;
  64809. this._reconstructedMesh.parent = this._mesh.parent;
  64810. this._reconstructedMesh.isVisible = false;
  64811. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  64812. };
  64813. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  64814. for (var i = 0; i < vertex1.triangleCount; ++i) {
  64815. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  64816. if (t.deleted)
  64817. continue;
  64818. var s = this.references[vertex1.triangleStart + i].vertexId;
  64819. var v1 = t.vertices[(s + 1) % 3];
  64820. var v2 = t.vertices[(s + 2) % 3];
  64821. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  64822. deletedArray[i] = true;
  64823. delTr.push(t);
  64824. continue;
  64825. }
  64826. var d1 = v1.position.subtract(point);
  64827. d1 = d1.normalize();
  64828. var d2 = v2.position.subtract(point);
  64829. d2 = d2.normalize();
  64830. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  64831. return true;
  64832. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  64833. deletedArray[i] = false;
  64834. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  64835. return true;
  64836. }
  64837. return false;
  64838. };
  64839. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  64840. var newDeleted = deletedTriangles;
  64841. for (var i = 0; i < vertex.triangleCount; ++i) {
  64842. var ref = this.references[vertex.triangleStart + i];
  64843. var t = this.triangles[ref.triangleId];
  64844. if (t.deleted)
  64845. continue;
  64846. if (deletedArray[i] && t.deletePending) {
  64847. t.deleted = true;
  64848. newDeleted++;
  64849. continue;
  64850. }
  64851. t.vertices[ref.vertexId] = origVertex;
  64852. t.isDirty = true;
  64853. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  64854. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  64855. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  64856. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  64857. this.references.push(ref);
  64858. }
  64859. return newDeleted;
  64860. };
  64861. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  64862. for (var i = 0; i < this.vertices.length; ++i) {
  64863. var vCount = [];
  64864. var vId = [];
  64865. var v = this.vertices[i];
  64866. var j;
  64867. for (j = 0; j < v.triangleCount; ++j) {
  64868. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  64869. for (var ii = 0; ii < 3; ii++) {
  64870. var ofs = 0;
  64871. var vv = triangle.vertices[ii];
  64872. while (ofs < vCount.length) {
  64873. if (vId[ofs] === vv.id)
  64874. break;
  64875. ++ofs;
  64876. }
  64877. if (ofs === vCount.length) {
  64878. vCount.push(1);
  64879. vId.push(vv.id);
  64880. }
  64881. else {
  64882. vCount[ofs]++;
  64883. }
  64884. }
  64885. }
  64886. for (j = 0; j < vCount.length; ++j) {
  64887. if (vCount[j] === 1) {
  64888. this.vertices[vId[j]].isBorder = true;
  64889. }
  64890. else {
  64891. this.vertices[vId[j]].isBorder = false;
  64892. }
  64893. }
  64894. }
  64895. };
  64896. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  64897. if (identifyBorders === void 0) { identifyBorders = false; }
  64898. var i;
  64899. if (!identifyBorders) {
  64900. var newTrianglesVector = [];
  64901. for (i = 0; i < this.triangles.length; ++i) {
  64902. if (!this.triangles[i].deleted) {
  64903. newTrianglesVector.push(this.triangles[i]);
  64904. }
  64905. }
  64906. this.triangles = newTrianglesVector;
  64907. }
  64908. for (i = 0; i < this.vertices.length; ++i) {
  64909. this.vertices[i].triangleCount = 0;
  64910. this.vertices[i].triangleStart = 0;
  64911. }
  64912. var t;
  64913. var j;
  64914. var v;
  64915. for (i = 0; i < this.triangles.length; ++i) {
  64916. t = this.triangles[i];
  64917. for (j = 0; j < 3; ++j) {
  64918. v = t.vertices[j];
  64919. v.triangleCount++;
  64920. }
  64921. }
  64922. var tStart = 0;
  64923. for (i = 0; i < this.vertices.length; ++i) {
  64924. this.vertices[i].triangleStart = tStart;
  64925. tStart += this.vertices[i].triangleCount;
  64926. this.vertices[i].triangleCount = 0;
  64927. }
  64928. var newReferences = new Array(this.triangles.length * 3);
  64929. for (i = 0; i < this.triangles.length; ++i) {
  64930. t = this.triangles[i];
  64931. for (j = 0; j < 3; ++j) {
  64932. v = t.vertices[j];
  64933. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  64934. v.triangleCount++;
  64935. }
  64936. }
  64937. this.references = newReferences;
  64938. if (identifyBorders) {
  64939. this.identifyBorder();
  64940. }
  64941. };
  64942. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  64943. var x = point.x;
  64944. var y = point.y;
  64945. var z = point.z;
  64946. 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
  64947. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  64948. };
  64949. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  64950. var q = vertex1.q.add(vertex2.q);
  64951. var border = vertex1.isBorder && vertex2.isBorder;
  64952. var error = 0;
  64953. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  64954. if (qDet !== 0 && !border) {
  64955. if (!pointResult) {
  64956. pointResult = BABYLON.Vector3.Zero();
  64957. }
  64958. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  64959. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  64960. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  64961. error = this.vertexError(q, pointResult);
  64962. }
  64963. else {
  64964. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  64965. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  64966. var error1 = this.vertexError(q, vertex1.position);
  64967. var error2 = this.vertexError(q, vertex2.position);
  64968. var error3 = this.vertexError(q, p3);
  64969. error = Math.min(error1, error2, error3);
  64970. if (error === error1) {
  64971. if (pointResult) {
  64972. pointResult.copyFrom(vertex1.position);
  64973. }
  64974. }
  64975. else if (error === error2) {
  64976. if (pointResult) {
  64977. pointResult.copyFrom(vertex2.position);
  64978. }
  64979. }
  64980. else {
  64981. if (pointResult) {
  64982. pointResult.copyFrom(p3);
  64983. }
  64984. }
  64985. }
  64986. return error;
  64987. };
  64988. return QuadraticErrorSimplification;
  64989. }());
  64990. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  64991. })(BABYLON || (BABYLON = {}));
  64992. //# sourceMappingURL=babylon.meshSimplification.js.map
  64993. var BABYLON;
  64994. (function (BABYLON) {
  64995. var Internals;
  64996. (function (Internals) {
  64997. var MeshLODLevel = (function () {
  64998. function MeshLODLevel(distance, mesh) {
  64999. this.distance = distance;
  65000. this.mesh = mesh;
  65001. }
  65002. return MeshLODLevel;
  65003. }());
  65004. Internals.MeshLODLevel = MeshLODLevel;
  65005. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65006. })(BABYLON || (BABYLON = {}));
  65007. //# sourceMappingURL=babylon.meshLODLevel.js.map
  65008. var BABYLON;
  65009. (function (BABYLON) {
  65010. // Standard optimizations
  65011. var SceneOptimization = (function () {
  65012. function SceneOptimization(priority) {
  65013. if (priority === void 0) { priority = 0; }
  65014. this.priority = priority;
  65015. this.apply = function (scene) {
  65016. return true; // Return true if everything that can be done was applied
  65017. };
  65018. }
  65019. return SceneOptimization;
  65020. }());
  65021. BABYLON.SceneOptimization = SceneOptimization;
  65022. var TextureOptimization = (function (_super) {
  65023. __extends(TextureOptimization, _super);
  65024. function TextureOptimization(priority, maximumSize) {
  65025. if (priority === void 0) { priority = 0; }
  65026. if (maximumSize === void 0) { maximumSize = 1024; }
  65027. var _this = _super.call(this, priority) || this;
  65028. _this.priority = priority;
  65029. _this.maximumSize = maximumSize;
  65030. _this.apply = function (scene) {
  65031. var allDone = true;
  65032. for (var index = 0; index < scene.textures.length; index++) {
  65033. var texture = scene.textures[index];
  65034. if (!texture.canRescale || texture.getContext) {
  65035. continue;
  65036. }
  65037. var currentSize = texture.getSize();
  65038. var maxDimension = Math.max(currentSize.width, currentSize.height);
  65039. if (maxDimension > _this.maximumSize) {
  65040. texture.scale(0.5);
  65041. allDone = false;
  65042. }
  65043. }
  65044. return allDone;
  65045. };
  65046. return _this;
  65047. }
  65048. return TextureOptimization;
  65049. }(SceneOptimization));
  65050. BABYLON.TextureOptimization = TextureOptimization;
  65051. var HardwareScalingOptimization = (function (_super) {
  65052. __extends(HardwareScalingOptimization, _super);
  65053. function HardwareScalingOptimization(priority, maximumScale) {
  65054. if (priority === void 0) { priority = 0; }
  65055. if (maximumScale === void 0) { maximumScale = 2; }
  65056. var _this = _super.call(this, priority) || this;
  65057. _this.priority = priority;
  65058. _this.maximumScale = maximumScale;
  65059. _this._currentScale = 1;
  65060. _this.apply = function (scene) {
  65061. _this._currentScale++;
  65062. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  65063. return _this._currentScale >= _this.maximumScale;
  65064. };
  65065. return _this;
  65066. }
  65067. return HardwareScalingOptimization;
  65068. }(SceneOptimization));
  65069. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  65070. var ShadowsOptimization = (function (_super) {
  65071. __extends(ShadowsOptimization, _super);
  65072. function ShadowsOptimization() {
  65073. var _this = _super !== null && _super.apply(this, arguments) || this;
  65074. _this.apply = function (scene) {
  65075. scene.shadowsEnabled = false;
  65076. return true;
  65077. };
  65078. return _this;
  65079. }
  65080. return ShadowsOptimization;
  65081. }(SceneOptimization));
  65082. BABYLON.ShadowsOptimization = ShadowsOptimization;
  65083. var PostProcessesOptimization = (function (_super) {
  65084. __extends(PostProcessesOptimization, _super);
  65085. function PostProcessesOptimization() {
  65086. var _this = _super !== null && _super.apply(this, arguments) || this;
  65087. _this.apply = function (scene) {
  65088. scene.postProcessesEnabled = false;
  65089. return true;
  65090. };
  65091. return _this;
  65092. }
  65093. return PostProcessesOptimization;
  65094. }(SceneOptimization));
  65095. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  65096. var LensFlaresOptimization = (function (_super) {
  65097. __extends(LensFlaresOptimization, _super);
  65098. function LensFlaresOptimization() {
  65099. var _this = _super !== null && _super.apply(this, arguments) || this;
  65100. _this.apply = function (scene) {
  65101. scene.lensFlaresEnabled = false;
  65102. return true;
  65103. };
  65104. return _this;
  65105. }
  65106. return LensFlaresOptimization;
  65107. }(SceneOptimization));
  65108. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  65109. var ParticlesOptimization = (function (_super) {
  65110. __extends(ParticlesOptimization, _super);
  65111. function ParticlesOptimization() {
  65112. var _this = _super !== null && _super.apply(this, arguments) || this;
  65113. _this.apply = function (scene) {
  65114. scene.particlesEnabled = false;
  65115. return true;
  65116. };
  65117. return _this;
  65118. }
  65119. return ParticlesOptimization;
  65120. }(SceneOptimization));
  65121. BABYLON.ParticlesOptimization = ParticlesOptimization;
  65122. var RenderTargetsOptimization = (function (_super) {
  65123. __extends(RenderTargetsOptimization, _super);
  65124. function RenderTargetsOptimization() {
  65125. var _this = _super !== null && _super.apply(this, arguments) || this;
  65126. _this.apply = function (scene) {
  65127. scene.renderTargetsEnabled = false;
  65128. return true;
  65129. };
  65130. return _this;
  65131. }
  65132. return RenderTargetsOptimization;
  65133. }(SceneOptimization));
  65134. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  65135. var MergeMeshesOptimization = (function (_super) {
  65136. __extends(MergeMeshesOptimization, _super);
  65137. function MergeMeshesOptimization() {
  65138. var _this = _super !== null && _super.apply(this, arguments) || this;
  65139. _this._canBeMerged = function (abstractMesh) {
  65140. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  65141. return false;
  65142. }
  65143. var mesh = abstractMesh;
  65144. if (!mesh.isVisible || !mesh.isEnabled()) {
  65145. return false;
  65146. }
  65147. if (mesh.instances.length > 0) {
  65148. return false;
  65149. }
  65150. if (mesh.skeleton || mesh.hasLODLevels) {
  65151. return false;
  65152. }
  65153. if (mesh.parent) {
  65154. return false;
  65155. }
  65156. return true;
  65157. };
  65158. _this.apply = function (scene, updateSelectionTree) {
  65159. var globalPool = scene.meshes.slice(0);
  65160. var globalLength = globalPool.length;
  65161. for (var index = 0; index < globalLength; index++) {
  65162. var currentPool = new Array();
  65163. var current = globalPool[index];
  65164. // Checks
  65165. if (!_this._canBeMerged(current)) {
  65166. continue;
  65167. }
  65168. currentPool.push(current);
  65169. // Find compatible meshes
  65170. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  65171. var otherMesh = globalPool[subIndex];
  65172. if (!_this._canBeMerged(otherMesh)) {
  65173. continue;
  65174. }
  65175. if (otherMesh.material !== current.material) {
  65176. continue;
  65177. }
  65178. if (otherMesh.checkCollisions !== current.checkCollisions) {
  65179. continue;
  65180. }
  65181. currentPool.push(otherMesh);
  65182. globalLength--;
  65183. globalPool.splice(subIndex, 1);
  65184. subIndex--;
  65185. }
  65186. if (currentPool.length < 2) {
  65187. continue;
  65188. }
  65189. // Merge meshes
  65190. BABYLON.Mesh.MergeMeshes(currentPool);
  65191. }
  65192. if (updateSelectionTree != undefined) {
  65193. if (updateSelectionTree) {
  65194. scene.createOrUpdateSelectionOctree();
  65195. }
  65196. }
  65197. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  65198. scene.createOrUpdateSelectionOctree();
  65199. }
  65200. return true;
  65201. };
  65202. return _this;
  65203. }
  65204. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  65205. get: function () {
  65206. return MergeMeshesOptimization._UpdateSelectionTree;
  65207. },
  65208. set: function (value) {
  65209. MergeMeshesOptimization._UpdateSelectionTree = value;
  65210. },
  65211. enumerable: true,
  65212. configurable: true
  65213. });
  65214. return MergeMeshesOptimization;
  65215. }(SceneOptimization));
  65216. MergeMeshesOptimization._UpdateSelectionTree = false;
  65217. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  65218. // Options
  65219. var SceneOptimizerOptions = (function () {
  65220. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  65221. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  65222. if (trackerDuration === void 0) { trackerDuration = 2000; }
  65223. this.targetFrameRate = targetFrameRate;
  65224. this.trackerDuration = trackerDuration;
  65225. this.optimizations = new Array();
  65226. }
  65227. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  65228. var result = new SceneOptimizerOptions(targetFrameRate);
  65229. var priority = 0;
  65230. result.optimizations.push(new MergeMeshesOptimization(priority));
  65231. result.optimizations.push(new ShadowsOptimization(priority));
  65232. result.optimizations.push(new LensFlaresOptimization(priority));
  65233. // Next priority
  65234. priority++;
  65235. result.optimizations.push(new PostProcessesOptimization(priority));
  65236. result.optimizations.push(new ParticlesOptimization(priority));
  65237. // Next priority
  65238. priority++;
  65239. result.optimizations.push(new TextureOptimization(priority, 1024));
  65240. return result;
  65241. };
  65242. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  65243. var result = new SceneOptimizerOptions(targetFrameRate);
  65244. var priority = 0;
  65245. result.optimizations.push(new MergeMeshesOptimization(priority));
  65246. result.optimizations.push(new ShadowsOptimization(priority));
  65247. result.optimizations.push(new LensFlaresOptimization(priority));
  65248. // Next priority
  65249. priority++;
  65250. result.optimizations.push(new PostProcessesOptimization(priority));
  65251. result.optimizations.push(new ParticlesOptimization(priority));
  65252. // Next priority
  65253. priority++;
  65254. result.optimizations.push(new TextureOptimization(priority, 512));
  65255. // Next priority
  65256. priority++;
  65257. result.optimizations.push(new RenderTargetsOptimization(priority));
  65258. // Next priority
  65259. priority++;
  65260. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  65261. return result;
  65262. };
  65263. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  65264. var result = new SceneOptimizerOptions(targetFrameRate);
  65265. var priority = 0;
  65266. result.optimizations.push(new MergeMeshesOptimization(priority));
  65267. result.optimizations.push(new ShadowsOptimization(priority));
  65268. result.optimizations.push(new LensFlaresOptimization(priority));
  65269. // Next priority
  65270. priority++;
  65271. result.optimizations.push(new PostProcessesOptimization(priority));
  65272. result.optimizations.push(new ParticlesOptimization(priority));
  65273. // Next priority
  65274. priority++;
  65275. result.optimizations.push(new TextureOptimization(priority, 256));
  65276. // Next priority
  65277. priority++;
  65278. result.optimizations.push(new RenderTargetsOptimization(priority));
  65279. // Next priority
  65280. priority++;
  65281. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  65282. return result;
  65283. };
  65284. return SceneOptimizerOptions;
  65285. }());
  65286. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  65287. // Scene optimizer tool
  65288. var SceneOptimizer = (function () {
  65289. function SceneOptimizer() {
  65290. }
  65291. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  65292. // TODO: add an epsilon
  65293. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  65294. if (onSuccess) {
  65295. onSuccess();
  65296. }
  65297. return;
  65298. }
  65299. // Apply current level of optimizations
  65300. var allDone = true;
  65301. var noOptimizationApplied = true;
  65302. for (var index = 0; index < options.optimizations.length; index++) {
  65303. var optimization = options.optimizations[index];
  65304. if (optimization.priority === currentPriorityLevel) {
  65305. noOptimizationApplied = false;
  65306. allDone = allDone && optimization.apply(scene);
  65307. }
  65308. }
  65309. // If no optimization was applied, this is a failure :(
  65310. if (noOptimizationApplied) {
  65311. if (onFailure) {
  65312. onFailure();
  65313. }
  65314. return;
  65315. }
  65316. // If all optimizations were done, move to next level
  65317. if (allDone) {
  65318. currentPriorityLevel++;
  65319. }
  65320. // Let's the system running for a specific amount of time before checking FPS
  65321. scene.executeWhenReady(function () {
  65322. setTimeout(function () {
  65323. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  65324. }, options.trackerDuration);
  65325. });
  65326. };
  65327. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  65328. if (!options) {
  65329. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  65330. }
  65331. // Let's the system running for a specific amount of time before checking FPS
  65332. scene.executeWhenReady(function () {
  65333. setTimeout(function () {
  65334. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  65335. }, options.trackerDuration);
  65336. });
  65337. };
  65338. return SceneOptimizer;
  65339. }());
  65340. BABYLON.SceneOptimizer = SceneOptimizer;
  65341. })(BABYLON || (BABYLON = {}));
  65342. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  65343. var BABYLON;
  65344. (function (BABYLON) {
  65345. var OutlineRenderer = (function () {
  65346. function OutlineRenderer(scene) {
  65347. this.zOffset = 1;
  65348. this._scene = scene;
  65349. }
  65350. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  65351. var _this = this;
  65352. if (useOverlay === void 0) { useOverlay = false; }
  65353. var scene = this._scene;
  65354. var engine = this._scene.getEngine();
  65355. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65356. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  65357. return;
  65358. }
  65359. var mesh = subMesh.getRenderingMesh();
  65360. var material = subMesh.getMaterial();
  65361. engine.enableEffect(this._effect);
  65362. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  65363. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  65364. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65365. // Bones
  65366. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65367. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65368. }
  65369. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65370. // Alpha test
  65371. if (material && material.needAlphaTesting()) {
  65372. var alphaTexture = material.getAlphaTestTexture();
  65373. this._effect.setTexture("diffuseSampler", alphaTexture);
  65374. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65375. }
  65376. engine.setZOffset(-this.zOffset);
  65377. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  65378. engine.setZOffset(0);
  65379. };
  65380. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  65381. var defines = [];
  65382. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  65383. var mesh = subMesh.getMesh();
  65384. var material = subMesh.getMaterial();
  65385. // Alpha test
  65386. if (material && material.needAlphaTesting()) {
  65387. defines.push("#define ALPHATEST");
  65388. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65389. attribs.push(BABYLON.VertexBuffer.UVKind);
  65390. defines.push("#define UV1");
  65391. }
  65392. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65393. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65394. defines.push("#define UV2");
  65395. }
  65396. }
  65397. // Bones
  65398. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65399. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65400. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65401. if (mesh.numBoneInfluencers > 4) {
  65402. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65403. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65404. }
  65405. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65406. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65407. }
  65408. else {
  65409. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65410. }
  65411. // Instances
  65412. if (useInstances) {
  65413. defines.push("#define INSTANCES");
  65414. attribs.push("world0");
  65415. attribs.push("world1");
  65416. attribs.push("world2");
  65417. attribs.push("world3");
  65418. }
  65419. // Get correct effect
  65420. var join = defines.join("\n");
  65421. if (this._cachedDefines !== join) {
  65422. this._cachedDefines = join;
  65423. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  65424. }
  65425. return this._effect.isReady();
  65426. };
  65427. return OutlineRenderer;
  65428. }());
  65429. BABYLON.OutlineRenderer = OutlineRenderer;
  65430. })(BABYLON || (BABYLON = {}));
  65431. //# sourceMappingURL=babylon.outlineRenderer.js.map
  65432. var BABYLON;
  65433. (function (BABYLON) {
  65434. var FaceAdjacencies = (function () {
  65435. function FaceAdjacencies() {
  65436. this.edges = new Array();
  65437. this.edgesConnectedCount = 0;
  65438. }
  65439. return FaceAdjacencies;
  65440. }());
  65441. var EdgesRenderer = (function () {
  65442. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  65443. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  65444. if (epsilon === void 0) { epsilon = 0.95; }
  65445. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  65446. this.edgesWidthScalerForOrthographic = 1000.0;
  65447. this.edgesWidthScalerForPerspective = 50.0;
  65448. this._linesPositions = new Array();
  65449. this._linesNormals = new Array();
  65450. this._linesIndices = new Array();
  65451. this._buffers = {};
  65452. this._checkVerticesInsteadOfIndices = false;
  65453. this._source = source;
  65454. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  65455. this._epsilon = epsilon;
  65456. this._prepareRessources();
  65457. this._generateEdgesLines();
  65458. }
  65459. EdgesRenderer.prototype._prepareRessources = function () {
  65460. if (this._lineShader) {
  65461. return;
  65462. }
  65463. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  65464. attributes: ["position", "normal"],
  65465. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  65466. });
  65467. this._lineShader.disableDepthWrite = true;
  65468. this._lineShader.backFaceCulling = false;
  65469. };
  65470. EdgesRenderer.prototype.dispose = function () {
  65471. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  65472. if (buffer) {
  65473. buffer.dispose();
  65474. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  65475. }
  65476. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  65477. if (buffer) {
  65478. buffer.dispose();
  65479. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  65480. }
  65481. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  65482. this._lineShader.dispose();
  65483. };
  65484. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  65485. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  65486. return 0;
  65487. }
  65488. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  65489. return 1;
  65490. }
  65491. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  65492. return 2;
  65493. }
  65494. return -1;
  65495. };
  65496. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  65497. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  65498. return 0;
  65499. }
  65500. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  65501. return 1;
  65502. }
  65503. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  65504. return 2;
  65505. }
  65506. return -1;
  65507. };
  65508. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  65509. var needToCreateLine;
  65510. if (edge === undefined) {
  65511. needToCreateLine = true;
  65512. }
  65513. else {
  65514. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  65515. needToCreateLine = dotProduct < this._epsilon;
  65516. }
  65517. if (needToCreateLine) {
  65518. var offset = this._linesPositions.length / 3;
  65519. var normal = p0.subtract(p1);
  65520. normal.normalize();
  65521. // Positions
  65522. this._linesPositions.push(p0.x);
  65523. this._linesPositions.push(p0.y);
  65524. this._linesPositions.push(p0.z);
  65525. this._linesPositions.push(p0.x);
  65526. this._linesPositions.push(p0.y);
  65527. this._linesPositions.push(p0.z);
  65528. this._linesPositions.push(p1.x);
  65529. this._linesPositions.push(p1.y);
  65530. this._linesPositions.push(p1.z);
  65531. this._linesPositions.push(p1.x);
  65532. this._linesPositions.push(p1.y);
  65533. this._linesPositions.push(p1.z);
  65534. // Normals
  65535. this._linesNormals.push(p1.x);
  65536. this._linesNormals.push(p1.y);
  65537. this._linesNormals.push(p1.z);
  65538. this._linesNormals.push(-1);
  65539. this._linesNormals.push(p1.x);
  65540. this._linesNormals.push(p1.y);
  65541. this._linesNormals.push(p1.z);
  65542. this._linesNormals.push(1);
  65543. this._linesNormals.push(p0.x);
  65544. this._linesNormals.push(p0.y);
  65545. this._linesNormals.push(p0.z);
  65546. this._linesNormals.push(-1);
  65547. this._linesNormals.push(p0.x);
  65548. this._linesNormals.push(p0.y);
  65549. this._linesNormals.push(p0.z);
  65550. this._linesNormals.push(1);
  65551. // Indices
  65552. this._linesIndices.push(offset);
  65553. this._linesIndices.push(offset + 1);
  65554. this._linesIndices.push(offset + 2);
  65555. this._linesIndices.push(offset);
  65556. this._linesIndices.push(offset + 2);
  65557. this._linesIndices.push(offset + 3);
  65558. }
  65559. };
  65560. EdgesRenderer.prototype._generateEdgesLines = function () {
  65561. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65562. var indices = this._source.getIndices();
  65563. // First let's find adjacencies
  65564. var adjacencies = new Array();
  65565. var faceNormals = new Array();
  65566. var index;
  65567. var faceAdjacencies;
  65568. // Prepare faces
  65569. for (index = 0; index < indices.length; index += 3) {
  65570. faceAdjacencies = new FaceAdjacencies();
  65571. var p0Index = indices[index];
  65572. var p1Index = indices[index + 1];
  65573. var p2Index = indices[index + 2];
  65574. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  65575. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  65576. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  65577. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  65578. faceNormal.normalize();
  65579. faceNormals.push(faceNormal);
  65580. adjacencies.push(faceAdjacencies);
  65581. }
  65582. // Scan
  65583. for (index = 0; index < adjacencies.length; index++) {
  65584. faceAdjacencies = adjacencies[index];
  65585. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  65586. var otherFaceAdjacencies = adjacencies[otherIndex];
  65587. if (faceAdjacencies.edgesConnectedCount === 3) {
  65588. break;
  65589. }
  65590. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  65591. continue;
  65592. }
  65593. var otherP0 = indices[otherIndex * 3];
  65594. var otherP1 = indices[otherIndex * 3 + 1];
  65595. var otherP2 = indices[otherIndex * 3 + 2];
  65596. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  65597. var otherEdgeIndex;
  65598. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  65599. continue;
  65600. }
  65601. switch (edgeIndex) {
  65602. case 0:
  65603. if (this._checkVerticesInsteadOfIndices) {
  65604. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65605. }
  65606. else {
  65607. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  65608. }
  65609. break;
  65610. case 1:
  65611. if (this._checkVerticesInsteadOfIndices) {
  65612. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65613. }
  65614. else {
  65615. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  65616. }
  65617. break;
  65618. case 2:
  65619. if (this._checkVerticesInsteadOfIndices) {
  65620. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65621. }
  65622. else {
  65623. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  65624. }
  65625. break;
  65626. }
  65627. if (otherEdgeIndex === -1) {
  65628. continue;
  65629. }
  65630. faceAdjacencies.edges[edgeIndex] = otherIndex;
  65631. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  65632. faceAdjacencies.edgesConnectedCount++;
  65633. otherFaceAdjacencies.edgesConnectedCount++;
  65634. if (faceAdjacencies.edgesConnectedCount === 3) {
  65635. break;
  65636. }
  65637. }
  65638. }
  65639. }
  65640. // Create lines
  65641. for (index = 0; index < adjacencies.length; index++) {
  65642. // 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
  65643. var current = adjacencies[index];
  65644. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  65645. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  65646. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  65647. }
  65648. // Merge into a single mesh
  65649. var engine = this._source.getScene().getEngine();
  65650. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  65651. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  65652. this._ib = engine.createIndexBuffer(this._linesIndices);
  65653. this._indicesCount = this._linesIndices.length;
  65654. };
  65655. EdgesRenderer.prototype.render = function () {
  65656. if (!this._lineShader.isReady()) {
  65657. return;
  65658. }
  65659. var scene = this._source.getScene();
  65660. var engine = scene.getEngine();
  65661. this._lineShader._preBind();
  65662. // VBOs
  65663. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  65664. scene.resetCachedMaterial();
  65665. this._lineShader.setColor4("color", this._source.edgesColor);
  65666. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  65667. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  65668. }
  65669. else {
  65670. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  65671. }
  65672. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  65673. this._lineShader.bind(this._source.getWorldMatrix());
  65674. // Draw order
  65675. engine.draw(true, 0, this._indicesCount);
  65676. this._lineShader.unbind();
  65677. engine.setDepthWrite(true);
  65678. };
  65679. return EdgesRenderer;
  65680. }());
  65681. BABYLON.EdgesRenderer = EdgesRenderer;
  65682. })(BABYLON || (BABYLON = {}));
  65683. //# sourceMappingURL=babylon.edgesRenderer.js.map
  65684. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  65685. /// <reference path="..\Math\babylon.math.ts" />
  65686. var BABYLON;
  65687. (function (BABYLON) {
  65688. /**
  65689. * Special Glow Blur post process only blurring the alpha channel
  65690. * It enforces keeping the most luminous color in the color channel.
  65691. */
  65692. var GlowBlurPostProcess = (function (_super) {
  65693. __extends(GlowBlurPostProcess, _super);
  65694. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  65695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65696. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  65697. _this.direction = direction;
  65698. _this.kernel = kernel;
  65699. _this.onApplyObservable.add(function (effect) {
  65700. effect.setFloat2("screenSize", _this.width, _this.height);
  65701. effect.setVector2("direction", _this.direction);
  65702. effect.setFloat("blurWidth", _this.kernel);
  65703. });
  65704. return _this;
  65705. }
  65706. return GlowBlurPostProcess;
  65707. }(BABYLON.PostProcess));
  65708. /**
  65709. * The highlight layer Helps adding a glow effect around a mesh.
  65710. *
  65711. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  65712. * glowy meshes to your scene.
  65713. *
  65714. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  65715. */
  65716. var HighlightLayer = (function () {
  65717. /**
  65718. * Instantiates a new highlight Layer and references it to the scene..
  65719. * @param name The name of the layer
  65720. * @param scene The scene to use the layer in
  65721. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  65722. */
  65723. function HighlightLayer(name, scene, options) {
  65724. this.name = name;
  65725. this._vertexBuffers = {};
  65726. this._mainTextureDesiredSize = { width: 0, height: 0 };
  65727. this._meshes = {};
  65728. this._maxSize = 0;
  65729. this._shouldRender = false;
  65730. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  65731. this._excludedMeshes = {};
  65732. /**
  65733. * Specifies whether or not the inner glow is ACTIVE in the layer.
  65734. */
  65735. this.innerGlow = true;
  65736. /**
  65737. * Specifies whether or not the outer glow is ACTIVE in the layer.
  65738. */
  65739. this.outerGlow = true;
  65740. /**
  65741. * Specifies wether the highlight layer is enabled or not.
  65742. */
  65743. this.isEnabled = true;
  65744. /**
  65745. * An event triggered when the highlight layer has been disposed.
  65746. * @type {BABYLON.Observable}
  65747. */
  65748. this.onDisposeObservable = new BABYLON.Observable();
  65749. /**
  65750. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  65751. * @type {BABYLON.Observable}
  65752. */
  65753. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  65754. /**
  65755. * An event triggered when the highlight layer is being blurred.
  65756. * @type {BABYLON.Observable}
  65757. */
  65758. this.onBeforeBlurObservable = new BABYLON.Observable();
  65759. /**
  65760. * An event triggered when the highlight layer has been blurred.
  65761. * @type {BABYLON.Observable}
  65762. */
  65763. this.onAfterBlurObservable = new BABYLON.Observable();
  65764. /**
  65765. * An event triggered when the glowing blurred texture is being merged in the scene.
  65766. * @type {BABYLON.Observable}
  65767. */
  65768. this.onBeforeComposeObservable = new BABYLON.Observable();
  65769. /**
  65770. * An event triggered when the glowing blurred texture has been merged in the scene.
  65771. * @type {BABYLON.Observable}
  65772. */
  65773. this.onAfterComposeObservable = new BABYLON.Observable();
  65774. /**
  65775. * An event triggered when the highlight layer changes its size.
  65776. * @type {BABYLON.Observable}
  65777. */
  65778. this.onSizeChangedObservable = new BABYLON.Observable();
  65779. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65780. var engine = scene.getEngine();
  65781. this._engine = engine;
  65782. this._maxSize = this._engine.getCaps().maxTextureSize;
  65783. this._scene.highlightLayers.push(this);
  65784. // Warn on stencil.
  65785. if (!this._engine.isStencilEnable) {
  65786. 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 }");
  65787. }
  65788. // Adapt options
  65789. this._options = options || {
  65790. mainTextureRatio: 0.5,
  65791. blurTextureSizeRatio: 0.5,
  65792. blurHorizontalSize: 1.0,
  65793. blurVerticalSize: 1.0,
  65794. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  65795. };
  65796. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  65797. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  65798. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  65799. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  65800. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  65801. // VBO
  65802. var vertices = [];
  65803. vertices.push(1, 1);
  65804. vertices.push(-1, 1);
  65805. vertices.push(-1, -1);
  65806. vertices.push(1, -1);
  65807. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65808. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  65809. // Indices
  65810. var indices = [];
  65811. indices.push(0);
  65812. indices.push(1);
  65813. indices.push(2);
  65814. indices.push(0);
  65815. indices.push(2);
  65816. indices.push(3);
  65817. this._indexBuffer = engine.createIndexBuffer(indices);
  65818. // Effect
  65819. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  65820. // Render target
  65821. this.setMainTextureSize();
  65822. // Create Textures and post processes
  65823. this.createTextureAndPostProcesses();
  65824. }
  65825. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  65826. /**
  65827. * Gets the horizontal size of the blur.
  65828. */
  65829. get: function () {
  65830. return this._horizontalBlurPostprocess.kernel;
  65831. },
  65832. /**
  65833. * Specifies the horizontal size of the blur.
  65834. */
  65835. set: function (value) {
  65836. this._horizontalBlurPostprocess.kernel = value;
  65837. },
  65838. enumerable: true,
  65839. configurable: true
  65840. });
  65841. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  65842. /**
  65843. * Gets the vertical size of the blur.
  65844. */
  65845. get: function () {
  65846. return this._verticalBlurPostprocess.kernel;
  65847. },
  65848. /**
  65849. * Specifies the vertical size of the blur.
  65850. */
  65851. set: function (value) {
  65852. this._verticalBlurPostprocess.kernel = value;
  65853. },
  65854. enumerable: true,
  65855. configurable: true
  65856. });
  65857. Object.defineProperty(HighlightLayer.prototype, "camera", {
  65858. /**
  65859. * Gets the camera attached to the layer.
  65860. */
  65861. get: function () {
  65862. return this._options.camera;
  65863. },
  65864. enumerable: true,
  65865. configurable: true
  65866. });
  65867. /**
  65868. * Creates the render target textures and post processes used in the highlight layer.
  65869. */
  65870. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  65871. var _this = this;
  65872. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  65873. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  65874. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  65875. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  65876. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  65877. width: this._mainTextureDesiredSize.width,
  65878. height: this._mainTextureDesiredSize.height
  65879. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65880. this._mainTexture.activeCamera = this._options.camera;
  65881. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65882. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65883. this._mainTexture.anisotropicFilteringLevel = 1;
  65884. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65885. this._mainTexture.renderParticles = false;
  65886. this._mainTexture.renderList = null;
  65887. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  65888. width: blurTextureWidth,
  65889. height: blurTextureHeight
  65890. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65891. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65892. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65893. this._blurTexture.anisotropicFilteringLevel = 16;
  65894. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65895. this._blurTexture.renderParticles = false;
  65896. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65897. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  65898. effect.setTexture("textureSampler", _this._mainTexture);
  65899. });
  65900. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  65901. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65902. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  65903. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65904. });
  65905. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65906. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  65907. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65908. });
  65909. }
  65910. else {
  65911. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65912. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  65913. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65914. });
  65915. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65916. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  65917. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65918. });
  65919. }
  65920. this._mainTexture.onAfterUnbindObservable.add(function () {
  65921. _this.onBeforeBlurObservable.notifyObservers(_this);
  65922. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  65923. _this.onAfterBlurObservable.notifyObservers(_this);
  65924. });
  65925. // Custom render function
  65926. var renderSubMesh = function (subMesh) {
  65927. var mesh = subMesh.getRenderingMesh();
  65928. var scene = _this._scene;
  65929. var engine = scene.getEngine();
  65930. // Culling
  65931. engine.setState(subMesh.getMaterial().backFaceCulling);
  65932. // Managing instances
  65933. var batch = mesh._getInstancesRenderList(subMesh._id);
  65934. if (batch.mustReturn) {
  65935. return;
  65936. }
  65937. // Excluded Mesh
  65938. if (_this._excludedMeshes[mesh.uniqueId]) {
  65939. return;
  65940. }
  65941. ;
  65942. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65943. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  65944. var material = subMesh.getMaterial();
  65945. var emissiveTexture = null;
  65946. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  65947. emissiveTexture = material.emissiveTexture;
  65948. }
  65949. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  65950. engine.enableEffect(_this._glowMapGenerationEffect);
  65951. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  65952. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  65953. if (highlightLayerMesh) {
  65954. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  65955. }
  65956. else {
  65957. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  65958. }
  65959. // Alpha test
  65960. if (material && material.needAlphaTesting()) {
  65961. var alphaTexture = material.getAlphaTestTexture();
  65962. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  65963. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65964. }
  65965. // Glow emissive only
  65966. if (emissiveTexture) {
  65967. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  65968. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  65969. }
  65970. // Bones
  65971. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65972. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65973. }
  65974. // Draw
  65975. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  65976. }
  65977. else {
  65978. // Need to reset refresh rate of the shadowMap
  65979. _this._mainTexture.resetRefreshCounter();
  65980. }
  65981. };
  65982. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  65983. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  65984. var index;
  65985. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65986. renderSubMesh(opaqueSubMeshes.data[index]);
  65987. }
  65988. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65989. renderSubMesh(alphaTestSubMeshes.data[index]);
  65990. }
  65991. for (index = 0; index < transparentSubMeshes.length; index++) {
  65992. renderSubMesh(transparentSubMeshes.data[index]);
  65993. }
  65994. };
  65995. this._mainTexture.onClearObservable.add(function (engine) {
  65996. engine.clear(HighlightLayer.neutralColor, true, true, true);
  65997. });
  65998. };
  65999. /**
  66000. * Checks for the readiness of the element composing the layer.
  66001. * @param subMesh the mesh to check for
  66002. * @param useInstances specify wether or not to use instances to render the mesh
  66003. * @param emissiveTexture the associated emissive texture used to generate the glow
  66004. * @return true if ready otherwise, false
  66005. */
  66006. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  66007. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  66008. return false;
  66009. }
  66010. var defines = [];
  66011. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66012. var mesh = subMesh.getMesh();
  66013. var material = subMesh.getMaterial();
  66014. var uv1 = false;
  66015. var uv2 = false;
  66016. // Alpha test
  66017. if (material && material.needAlphaTesting()) {
  66018. var alphaTexture = material.getAlphaTestTexture();
  66019. if (alphaTexture) {
  66020. defines.push("#define ALPHATEST");
  66021. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  66022. alphaTexture.coordinatesIndex === 1) {
  66023. defines.push("#define DIFFUSEUV2");
  66024. uv2 = true;
  66025. }
  66026. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66027. defines.push("#define DIFFUSEUV1");
  66028. uv1 = true;
  66029. }
  66030. }
  66031. }
  66032. // Emissive
  66033. if (emissiveTexture) {
  66034. defines.push("#define EMISSIVE");
  66035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  66036. emissiveTexture.coordinatesIndex === 1) {
  66037. defines.push("#define EMISSIVEUV2");
  66038. uv2 = true;
  66039. }
  66040. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66041. defines.push("#define EMISSIVEUV1");
  66042. uv1 = true;
  66043. }
  66044. }
  66045. if (uv1) {
  66046. attribs.push(BABYLON.VertexBuffer.UVKind);
  66047. defines.push("#define UV1");
  66048. }
  66049. if (uv2) {
  66050. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66051. defines.push("#define UV2");
  66052. }
  66053. // Bones
  66054. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66055. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66056. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66057. if (mesh.numBoneInfluencers > 4) {
  66058. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66059. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66060. }
  66061. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66062. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66063. }
  66064. else {
  66065. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66066. }
  66067. // Instances
  66068. if (useInstances) {
  66069. defines.push("#define INSTANCES");
  66070. attribs.push("world0");
  66071. attribs.push("world1");
  66072. attribs.push("world2");
  66073. attribs.push("world3");
  66074. }
  66075. // Get correct effect
  66076. var join = defines.join("\n");
  66077. if (this._cachedDefines !== join) {
  66078. this._cachedDefines = join;
  66079. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  66080. }
  66081. return this._glowMapGenerationEffect.isReady();
  66082. };
  66083. /**
  66084. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  66085. */
  66086. HighlightLayer.prototype.render = function () {
  66087. var currentEffect = this._glowMapMergeEffect;
  66088. // Check
  66089. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  66090. return;
  66091. var engine = this._scene.getEngine();
  66092. this.onBeforeComposeObservable.notifyObservers(this);
  66093. // Render
  66094. engine.enableEffect(currentEffect);
  66095. engine.setState(false);
  66096. // Cache
  66097. var previousStencilBuffer = engine.getStencilBuffer();
  66098. var previousStencilFunction = engine.getStencilFunction();
  66099. var previousStencilMask = engine.getStencilMask();
  66100. var previousStencilOperationPass = engine.getStencilOperationPass();
  66101. var previousStencilOperationFail = engine.getStencilOperationFail();
  66102. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  66103. var previousAlphaMode = engine.getAlphaMode();
  66104. // Texture
  66105. currentEffect.setTexture("textureSampler", this._blurTexture);
  66106. // VBOs
  66107. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  66108. // Stencil operations
  66109. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  66110. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  66111. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  66112. // Draw order
  66113. engine.setAlphaMode(this._options.alphaBlendingMode);
  66114. engine.setStencilMask(0x00);
  66115. engine.setStencilBuffer(true);
  66116. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  66117. if (this.outerGlow) {
  66118. currentEffect.setFloat("offset", 0);
  66119. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  66120. engine.draw(true, 0, 6);
  66121. }
  66122. if (this.innerGlow) {
  66123. currentEffect.setFloat("offset", 1);
  66124. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  66125. engine.draw(true, 0, 6);
  66126. }
  66127. // Restore Cache
  66128. engine.setStencilFunction(previousStencilFunction);
  66129. engine.setStencilMask(previousStencilMask);
  66130. engine.setAlphaMode(previousAlphaMode);
  66131. engine.setStencilBuffer(previousStencilBuffer);
  66132. engine.setStencilOperationPass(previousStencilOperationPass);
  66133. engine.setStencilOperationFail(previousStencilOperationFail);
  66134. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  66135. engine._stencilState.reset();
  66136. this.onAfterComposeObservable.notifyObservers(this);
  66137. // Handle size changes.
  66138. var size = this._mainTexture.getSize();
  66139. this.setMainTextureSize();
  66140. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  66141. // Recreate RTT and post processes on size change.
  66142. this.onSizeChangedObservable.notifyObservers(this);
  66143. this.disposeTextureAndPostProcesses();
  66144. this.createTextureAndPostProcesses();
  66145. }
  66146. };
  66147. /**
  66148. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  66149. * @param mesh The mesh to exclude from the highlight layer
  66150. */
  66151. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  66152. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  66153. if (!meshExcluded) {
  66154. this._excludedMeshes[mesh.uniqueId] = {
  66155. mesh: mesh,
  66156. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  66157. mesh.getEngine().setStencilBuffer(false);
  66158. }),
  66159. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  66160. mesh.getEngine().setStencilBuffer(true);
  66161. }),
  66162. };
  66163. }
  66164. };
  66165. /**
  66166. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  66167. * @param mesh The mesh to highlight
  66168. */
  66169. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  66170. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  66171. if (meshExcluded) {
  66172. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  66173. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  66174. }
  66175. this._excludedMeshes[mesh.uniqueId] = undefined;
  66176. };
  66177. /**
  66178. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  66179. * @param mesh The mesh to highlight
  66180. * @param color The color of the highlight
  66181. * @param glowEmissiveOnly Extract the glow from the emissive texture
  66182. */
  66183. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  66184. var _this = this;
  66185. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  66186. var meshHighlight = this._meshes[mesh.uniqueId];
  66187. if (meshHighlight) {
  66188. meshHighlight.color = color;
  66189. }
  66190. else {
  66191. this._meshes[mesh.uniqueId] = {
  66192. mesh: mesh,
  66193. color: color,
  66194. // Lambda required for capture due to Observable this context
  66195. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  66196. if (_this._excludedMeshes[mesh.uniqueId]) {
  66197. _this.defaultStencilReference(mesh);
  66198. }
  66199. else {
  66200. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  66201. }
  66202. }),
  66203. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  66204. glowEmissiveOnly: glowEmissiveOnly
  66205. };
  66206. }
  66207. this._shouldRender = true;
  66208. };
  66209. /**
  66210. * Remove a mesh from the highlight layer in order to make it stop glowing.
  66211. * @param mesh The mesh to highlight
  66212. */
  66213. HighlightLayer.prototype.removeMesh = function (mesh) {
  66214. var meshHighlight = this._meshes[mesh.uniqueId];
  66215. if (meshHighlight) {
  66216. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  66217. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  66218. }
  66219. this._meshes[mesh.uniqueId] = undefined;
  66220. this._shouldRender = false;
  66221. for (var meshHighlightToCheck in this._meshes) {
  66222. if (meshHighlightToCheck) {
  66223. this._shouldRender = true;
  66224. break;
  66225. }
  66226. }
  66227. };
  66228. /**
  66229. * Returns true if the layer contains information to display, otherwise false.
  66230. */
  66231. HighlightLayer.prototype.shouldRender = function () {
  66232. return this.isEnabled && this._shouldRender;
  66233. };
  66234. /**
  66235. * Sets the main texture desired size which is the closest power of two
  66236. * of the engine canvas size.
  66237. */
  66238. HighlightLayer.prototype.setMainTextureSize = function () {
  66239. if (this._options.mainTextureFixedSize) {
  66240. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  66241. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  66242. }
  66243. else {
  66244. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  66245. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  66246. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  66247. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  66248. }
  66249. };
  66250. /**
  66251. * Force the stencil to the normal expected value for none glowing parts
  66252. */
  66253. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  66254. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  66255. };
  66256. /**
  66257. * Dispose only the render target textures and post process.
  66258. */
  66259. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  66260. this._blurTexture.dispose();
  66261. this._mainTexture.dispose();
  66262. this._downSamplePostprocess.dispose();
  66263. this._horizontalBlurPostprocess.dispose();
  66264. this._verticalBlurPostprocess.dispose();
  66265. };
  66266. /**
  66267. * Dispose the highlight layer and free resources.
  66268. */
  66269. HighlightLayer.prototype.dispose = function () {
  66270. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66271. if (vertexBuffer) {
  66272. vertexBuffer.dispose();
  66273. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66274. }
  66275. if (this._indexBuffer) {
  66276. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66277. this._indexBuffer = null;
  66278. }
  66279. // Clean textures and post processes
  66280. this.disposeTextureAndPostProcesses();
  66281. // Clean mesh references
  66282. for (var id in this._meshes) {
  66283. var meshHighlight = this._meshes[id];
  66284. if (meshHighlight && meshHighlight.mesh) {
  66285. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  66286. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  66287. }
  66288. }
  66289. this._meshes = null;
  66290. for (var id in this._excludedMeshes) {
  66291. var meshHighlight = this._excludedMeshes[id];
  66292. if (meshHighlight) {
  66293. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  66294. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  66295. }
  66296. }
  66297. this._excludedMeshes = null;
  66298. // Remove from scene
  66299. var index = this._scene.highlightLayers.indexOf(this, 0);
  66300. if (index > -1) {
  66301. this._scene.highlightLayers.splice(index, 1);
  66302. }
  66303. // Callback
  66304. this.onDisposeObservable.notifyObservers(this);
  66305. this.onDisposeObservable.clear();
  66306. this.onBeforeRenderMainTextureObservable.clear();
  66307. this.onBeforeBlurObservable.clear();
  66308. this.onBeforeComposeObservable.clear();
  66309. this.onAfterComposeObservable.clear();
  66310. this.onSizeChangedObservable.clear();
  66311. };
  66312. return HighlightLayer;
  66313. }());
  66314. /**
  66315. * The neutral color used during the preparation of the glow effect.
  66316. * This is black by default as the blend operation is a blend operation.
  66317. */
  66318. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  66319. /**
  66320. * Stencil value used for glowing meshes.
  66321. */
  66322. HighlightLayer.glowingMeshStencilReference = 0x02;
  66323. /**
  66324. * Stencil value used for the other meshes in the scene.
  66325. */
  66326. HighlightLayer.normalMeshStencilReference = 0x01;
  66327. BABYLON.HighlightLayer = HighlightLayer;
  66328. })(BABYLON || (BABYLON = {}));
  66329. //# sourceMappingURL=babylon.highlightlayer.js.map
  66330. var BABYLON;
  66331. (function (BABYLON) {
  66332. var MeshAssetTask = (function () {
  66333. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  66334. this.name = name;
  66335. this.meshesNames = meshesNames;
  66336. this.rootUrl = rootUrl;
  66337. this.sceneFilename = sceneFilename;
  66338. this.isCompleted = false;
  66339. }
  66340. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66341. var _this = this;
  66342. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  66343. _this.loadedMeshes = meshes;
  66344. _this.loadedParticleSystems = particleSystems;
  66345. _this.loadedSkeletons = skeletons;
  66346. _this.isCompleted = true;
  66347. if (_this.onSuccess) {
  66348. _this.onSuccess(_this);
  66349. }
  66350. onSuccess();
  66351. }, null, function () {
  66352. if (_this.onError) {
  66353. _this.onError(_this);
  66354. }
  66355. onError();
  66356. });
  66357. };
  66358. return MeshAssetTask;
  66359. }());
  66360. BABYLON.MeshAssetTask = MeshAssetTask;
  66361. var TextFileAssetTask = (function () {
  66362. function TextFileAssetTask(name, url) {
  66363. this.name = name;
  66364. this.url = url;
  66365. this.isCompleted = false;
  66366. }
  66367. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66368. var _this = this;
  66369. BABYLON.Tools.LoadFile(this.url, function (data) {
  66370. _this.text = data;
  66371. _this.isCompleted = true;
  66372. if (_this.onSuccess) {
  66373. _this.onSuccess(_this);
  66374. }
  66375. onSuccess();
  66376. }, null, scene.database, false, function () {
  66377. if (_this.onError) {
  66378. _this.onError(_this);
  66379. }
  66380. onError();
  66381. });
  66382. };
  66383. return TextFileAssetTask;
  66384. }());
  66385. BABYLON.TextFileAssetTask = TextFileAssetTask;
  66386. var BinaryFileAssetTask = (function () {
  66387. function BinaryFileAssetTask(name, url) {
  66388. this.name = name;
  66389. this.url = url;
  66390. this.isCompleted = false;
  66391. }
  66392. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66393. var _this = this;
  66394. BABYLON.Tools.LoadFile(this.url, function (data) {
  66395. _this.data = data;
  66396. _this.isCompleted = true;
  66397. if (_this.onSuccess) {
  66398. _this.onSuccess(_this);
  66399. }
  66400. onSuccess();
  66401. }, null, scene.database, true, function () {
  66402. if (_this.onError) {
  66403. _this.onError(_this);
  66404. }
  66405. onError();
  66406. });
  66407. };
  66408. return BinaryFileAssetTask;
  66409. }());
  66410. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  66411. var ImageAssetTask = (function () {
  66412. function ImageAssetTask(name, url) {
  66413. this.name = name;
  66414. this.url = url;
  66415. this.isCompleted = false;
  66416. }
  66417. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66418. var _this = this;
  66419. var img = new Image();
  66420. BABYLON.Tools.SetCorsBehavior(this.url, img);
  66421. img.onload = function () {
  66422. _this.image = img;
  66423. _this.isCompleted = true;
  66424. if (_this.onSuccess) {
  66425. _this.onSuccess(_this);
  66426. }
  66427. onSuccess();
  66428. };
  66429. img.onerror = function () {
  66430. if (_this.onError) {
  66431. _this.onError(_this);
  66432. }
  66433. onError();
  66434. };
  66435. img.src = this.url;
  66436. };
  66437. return ImageAssetTask;
  66438. }());
  66439. BABYLON.ImageAssetTask = ImageAssetTask;
  66440. var TextureAssetTask = (function () {
  66441. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  66442. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66443. this.name = name;
  66444. this.url = url;
  66445. this.noMipmap = noMipmap;
  66446. this.invertY = invertY;
  66447. this.samplingMode = samplingMode;
  66448. this.isCompleted = false;
  66449. }
  66450. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66451. var _this = this;
  66452. var onload = function () {
  66453. _this.isCompleted = true;
  66454. if (_this.onSuccess) {
  66455. _this.onSuccess(_this);
  66456. }
  66457. onSuccess();
  66458. };
  66459. var onerror = function () {
  66460. if (_this.onError) {
  66461. _this.onError(_this);
  66462. }
  66463. onError();
  66464. };
  66465. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  66466. };
  66467. return TextureAssetTask;
  66468. }());
  66469. BABYLON.TextureAssetTask = TextureAssetTask;
  66470. var CubeTextureAssetTask = (function () {
  66471. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  66472. this.name = name;
  66473. this.url = url;
  66474. this.extensions = extensions;
  66475. this.noMipmap = noMipmap;
  66476. this.files = files;
  66477. this.isCompleted = false;
  66478. }
  66479. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66480. var _this = this;
  66481. var onload = function () {
  66482. _this.isCompleted = true;
  66483. if (_this.onSuccess) {
  66484. _this.onSuccess(_this);
  66485. }
  66486. onSuccess();
  66487. };
  66488. var onerror = function () {
  66489. if (_this.onError) {
  66490. _this.onError(_this);
  66491. }
  66492. onError();
  66493. };
  66494. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  66495. };
  66496. return CubeTextureAssetTask;
  66497. }());
  66498. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  66499. var HDRCubeTextureAssetTask = (function () {
  66500. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  66501. if (noMipmap === void 0) { noMipmap = false; }
  66502. if (generateHarmonics === void 0) { generateHarmonics = true; }
  66503. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  66504. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  66505. this.name = name;
  66506. this.url = url;
  66507. this.size = size;
  66508. this.noMipmap = noMipmap;
  66509. this.generateHarmonics = generateHarmonics;
  66510. this.useInGammaSpace = useInGammaSpace;
  66511. this.usePMREMGenerator = usePMREMGenerator;
  66512. this.isCompleted = false;
  66513. }
  66514. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66515. var _this = this;
  66516. var onload = function () {
  66517. _this.isCompleted = true;
  66518. if (_this.onSuccess) {
  66519. _this.onSuccess(_this);
  66520. }
  66521. onSuccess();
  66522. };
  66523. var onerror = function () {
  66524. if (_this.onError) {
  66525. _this.onError(_this);
  66526. }
  66527. onError();
  66528. };
  66529. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  66530. };
  66531. return HDRCubeTextureAssetTask;
  66532. }());
  66533. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  66534. var AssetsManager = (function () {
  66535. function AssetsManager(scene) {
  66536. this.tasks = new Array();
  66537. this.waitingTasksCount = 0;
  66538. this.useDefaultLoadingScreen = true;
  66539. this._scene = scene;
  66540. }
  66541. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  66542. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  66543. this.tasks.push(task);
  66544. return task;
  66545. };
  66546. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  66547. var task = new TextFileAssetTask(taskName, url);
  66548. this.tasks.push(task);
  66549. return task;
  66550. };
  66551. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  66552. var task = new BinaryFileAssetTask(taskName, url);
  66553. this.tasks.push(task);
  66554. return task;
  66555. };
  66556. AssetsManager.prototype.addImageTask = function (taskName, url) {
  66557. var task = new ImageAssetTask(taskName, url);
  66558. this.tasks.push(task);
  66559. return task;
  66560. };
  66561. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  66562. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66563. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  66564. this.tasks.push(task);
  66565. return task;
  66566. };
  66567. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  66568. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  66569. this.tasks.push(task);
  66570. return task;
  66571. };
  66572. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  66573. if (noMipmap === void 0) { noMipmap = false; }
  66574. if (generateHarmonics === void 0) { generateHarmonics = true; }
  66575. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  66576. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  66577. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  66578. this.tasks.push(task);
  66579. return task;
  66580. };
  66581. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  66582. this.waitingTasksCount--;
  66583. if (this.waitingTasksCount === 0) {
  66584. if (this.onFinish) {
  66585. this.onFinish(this.tasks);
  66586. }
  66587. this._scene.getEngine().hideLoadingUI();
  66588. }
  66589. };
  66590. AssetsManager.prototype._runTask = function (task) {
  66591. var _this = this;
  66592. task.run(this._scene, function () {
  66593. if (_this.onTaskSuccess) {
  66594. _this.onTaskSuccess(task);
  66595. }
  66596. _this._decreaseWaitingTasksCount();
  66597. }, function () {
  66598. if (_this.onTaskError) {
  66599. _this.onTaskError(task);
  66600. }
  66601. _this._decreaseWaitingTasksCount();
  66602. });
  66603. };
  66604. AssetsManager.prototype.reset = function () {
  66605. this.tasks = new Array();
  66606. return this;
  66607. };
  66608. AssetsManager.prototype.load = function () {
  66609. this.waitingTasksCount = this.tasks.length;
  66610. if (this.waitingTasksCount === 0) {
  66611. if (this.onFinish) {
  66612. this.onFinish(this.tasks);
  66613. }
  66614. return this;
  66615. }
  66616. if (this.useDefaultLoadingScreen) {
  66617. this._scene.getEngine().displayLoadingUI();
  66618. }
  66619. for (var index = 0; index < this.tasks.length; index++) {
  66620. var task = this.tasks[index];
  66621. this._runTask(task);
  66622. }
  66623. return this;
  66624. };
  66625. return AssetsManager;
  66626. }());
  66627. BABYLON.AssetsManager = AssetsManager;
  66628. })(BABYLON || (BABYLON = {}));
  66629. //# sourceMappingURL=babylon.assetsManager.js.map
  66630. var BABYLON;
  66631. (function (BABYLON) {
  66632. var MapTexture = (function (_super) {
  66633. __extends(MapTexture, _super);
  66634. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  66635. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66636. if (useMipMap === void 0) { useMipMap = false; }
  66637. if (margin === void 0) { margin = 0; }
  66638. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  66639. _this.name = name;
  66640. _this._size = size;
  66641. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66642. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66643. // Create the rectPackMap that will allocate portion of the texture
  66644. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  66645. // Create the texture that will store the content
  66646. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  66647. return _this;
  66648. }
  66649. /**
  66650. * Allocate a rectangle of a given size in the texture map
  66651. * @param size the size of the rectangle to allocation
  66652. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  66653. */
  66654. MapTexture.prototype.allocateRect = function (size) {
  66655. return this._rectPackingMap.addRect(size);
  66656. };
  66657. /**
  66658. * Free a given rectangle from the texture map
  66659. * @param rectInfo the instance corresponding to the rect to free.
  66660. */
  66661. MapTexture.prototype.freeRect = function (rectInfo) {
  66662. if (rectInfo) {
  66663. rectInfo.freeContent();
  66664. }
  66665. };
  66666. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  66667. /**
  66668. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  66669. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  66670. * @returns {}
  66671. */
  66672. get: function () {
  66673. return this._rectPackingMap.freeSpace;
  66674. },
  66675. enumerable: true,
  66676. configurable: true
  66677. });
  66678. /**
  66679. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  66680. * 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.
  66681. * Don't forget to call unbindTexture when you're done rendering
  66682. * @param rect the zone to render to
  66683. * @param clear true to clear the portion's color/depth data
  66684. */
  66685. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  66686. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  66687. };
  66688. /**
  66689. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  66690. * 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.
  66691. * Don't forget to call unbindTexture when you're done rendering
  66692. * @param pos the position into the texture
  66693. * @param size the portion to fit the clip space to
  66694. * @param clear true to clear the portion's color/depth data
  66695. */
  66696. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  66697. var engine = this.getScene().getEngine();
  66698. engine.bindFramebuffer(this._texture);
  66699. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  66700. if (clear) {
  66701. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  66702. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  66703. }
  66704. };
  66705. /**
  66706. * Unbind the texture map from the rendering engine.
  66707. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  66708. * @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.
  66709. */
  66710. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  66711. // Dump ?
  66712. if (dumpForDebug) {
  66713. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  66714. }
  66715. var engine = this.getScene().getEngine();
  66716. if (this._replacedViewport) {
  66717. engine.setViewport(this._replacedViewport);
  66718. this._replacedViewport = null;
  66719. }
  66720. engine.unBindFramebuffer(this._texture);
  66721. };
  66722. Object.defineProperty(MapTexture.prototype, "canRescale", {
  66723. get: function () {
  66724. return false;
  66725. },
  66726. enumerable: true,
  66727. configurable: true
  66728. });
  66729. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  66730. // Anyway, there's not much point to use this method for this kind of texture I guess
  66731. MapTexture.prototype.clone = function () {
  66732. return null;
  66733. };
  66734. return MapTexture;
  66735. }(BABYLON.Texture));
  66736. BABYLON.MapTexture = MapTexture;
  66737. })(BABYLON || (BABYLON = {}));
  66738. //# sourceMappingURL=babylon.mapTexture.js.map
  66739. var BABYLON;
  66740. (function (BABYLON) {
  66741. /**
  66742. * This class describe a rectangle that were added to the map.
  66743. * You have access to its coordinates either in pixel or normalized (UV)
  66744. */
  66745. var PackedRect = (function () {
  66746. function PackedRect(root, parent, pos, size) {
  66747. this._pos = pos;
  66748. this._size = size;
  66749. this._root = root;
  66750. this._parent = parent;
  66751. this._contentSize = null;
  66752. this._bottomNode = null;
  66753. this._leftNode = null;
  66754. this._initialSize = null;
  66755. this._rightNode = null;
  66756. }
  66757. Object.defineProperty(PackedRect.prototype, "pos", {
  66758. /**
  66759. * @returns the position of this node into the map
  66760. */
  66761. get: function () {
  66762. return this._pos;
  66763. },
  66764. enumerable: true,
  66765. configurable: true
  66766. });
  66767. Object.defineProperty(PackedRect.prototype, "contentSize", {
  66768. /**
  66769. * @returns the size of the rectangle this node handles
  66770. */
  66771. get: function () {
  66772. return this._contentSize;
  66773. },
  66774. enumerable: true,
  66775. configurable: true
  66776. });
  66777. /**
  66778. * Retrieve the inner position (considering the margin) and stores it into the res object
  66779. * @param res must be a valid Vector2 that will contain the inner position after this call
  66780. */
  66781. PackedRect.prototype.getInnerPosToRef = function (res) {
  66782. var m = this._root._margin;
  66783. res.x = this._pos.x + m;
  66784. res.y = this._pos.y + m;
  66785. };
  66786. /**
  66787. * Retrieve the inner size (considering the margin) and stores it into the res object
  66788. * @param res must be a valid Size that will contain the inner size after this call
  66789. */
  66790. PackedRect.prototype.getInnerSizeToRef = function (res) {
  66791. var m = this._root._margin;
  66792. res.width = this._contentSize.width - (m * 2);
  66793. res.height = this._contentSize.height - (m * 2);
  66794. };
  66795. Object.defineProperty(PackedRect.prototype, "UVs", {
  66796. /**
  66797. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  66798. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  66799. */
  66800. get: function () {
  66801. if (!this._contentSize) {
  66802. throw new Error("Can't compute UVs for this object because it's nor allocated");
  66803. }
  66804. return this.getUVsForCustomSize(this._contentSize);
  66805. },
  66806. enumerable: true,
  66807. configurable: true
  66808. });
  66809. /**
  66810. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  66811. * and then using only a part of the PackRect.
  66812. * This method will return the UVs for this part by given the custom size of what you really use
  66813. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  66814. */
  66815. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  66816. var mainWidth = this._root._size.width;
  66817. var mainHeight = this._root._size.height;
  66818. var margin = this._root._margin;
  66819. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  66820. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  66821. var uvs = new Array();
  66822. uvs.push(topLeft);
  66823. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  66824. uvs.push(rightBottom);
  66825. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  66826. return uvs;
  66827. };
  66828. /**
  66829. * Free this rectangle from the map.
  66830. * Call this method when you no longer need the rectangle to be in the map.
  66831. */
  66832. PackedRect.prototype.freeContent = function () {
  66833. if (!this.contentSize) {
  66834. return;
  66835. }
  66836. this._contentSize = null;
  66837. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  66838. this.attemptDefrag();
  66839. };
  66840. Object.defineProperty(PackedRect.prototype, "isUsed", {
  66841. get: function () {
  66842. return this._contentSize != null || this._leftNode != null;
  66843. },
  66844. enumerable: true,
  66845. configurable: true
  66846. });
  66847. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  66848. var node = this.findNode(contentSize);
  66849. // Not enough space...
  66850. if (!node) {
  66851. return null;
  66852. }
  66853. node.splitNode(contentSize);
  66854. return node;
  66855. };
  66856. PackedRect.prototype.findNode = function (size) {
  66857. var resNode = null;
  66858. var margin = this._root._margin * 2;
  66859. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  66860. if (this.isUsed) {
  66861. if (this._leftNode) {
  66862. resNode = this._leftNode.findNode(size);
  66863. }
  66864. if (!resNode && this._rightNode) {
  66865. resNode = this._rightNode.findNode(size);
  66866. }
  66867. if (!resNode && this._bottomNode) {
  66868. resNode = this._bottomNode.findNode(size);
  66869. }
  66870. }
  66871. else if (this._initialSize) {
  66872. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  66873. resNode = this;
  66874. }
  66875. else {
  66876. return null;
  66877. }
  66878. }
  66879. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  66880. resNode = this;
  66881. }
  66882. return resNode;
  66883. };
  66884. PackedRect.prototype.splitNode = function (contentSize) {
  66885. var cs = PackedRect.TpsSize;
  66886. var margin = this._root._margin * 2;
  66887. cs.copyFrom(contentSize);
  66888. cs.width += margin;
  66889. cs.height += margin;
  66890. // 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)
  66891. if (!this._contentSize && this._initialSize) {
  66892. this._contentSize = cs.clone();
  66893. 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));
  66894. return this._leftNode.splitNode(contentSize);
  66895. }
  66896. else {
  66897. this._contentSize = cs.clone();
  66898. this._initialSize = cs.clone();
  66899. if (cs.width !== this._size.width) {
  66900. 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));
  66901. }
  66902. if (cs.height !== this._size.height) {
  66903. 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));
  66904. }
  66905. return this;
  66906. }
  66907. };
  66908. PackedRect.prototype.attemptDefrag = function () {
  66909. if (!this.isUsed && this.isRecursiveFree) {
  66910. this.clearNode();
  66911. if (this._parent) {
  66912. this._parent.attemptDefrag();
  66913. }
  66914. }
  66915. };
  66916. PackedRect.prototype.clearNode = function () {
  66917. this._initialSize = null;
  66918. this._rightNode = null;
  66919. this._bottomNode = null;
  66920. };
  66921. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  66922. get: function () {
  66923. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  66924. },
  66925. enumerable: true,
  66926. configurable: true
  66927. });
  66928. PackedRect.prototype.evalFreeSize = function (size) {
  66929. var levelSize = 0;
  66930. if (!this.isUsed) {
  66931. var margin = this._root._margin;
  66932. var is = this._initialSize;
  66933. if (is) {
  66934. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  66935. }
  66936. else {
  66937. var size_1 = this._size;
  66938. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  66939. }
  66940. }
  66941. if (this._rightNode) {
  66942. levelSize += this._rightNode.evalFreeSize(0);
  66943. }
  66944. if (this._bottomNode) {
  66945. levelSize += this._bottomNode.evalFreeSize(0);
  66946. }
  66947. return levelSize + size;
  66948. };
  66949. return PackedRect;
  66950. }());
  66951. PackedRect.TpsSize = BABYLON.Size.Zero();
  66952. BABYLON.PackedRect = PackedRect;
  66953. /**
  66954. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  66955. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  66956. * 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.
  66957. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  66958. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  66959. */
  66960. var RectPackingMap = (function (_super) {
  66961. __extends(RectPackingMap, _super);
  66962. /**
  66963. * Create an instance of the object with a dimension using the given size
  66964. * @param size The dimension of the rectangle that will contain all the sub ones.
  66965. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  66966. */
  66967. function RectPackingMap(size, margin) {
  66968. if (margin === void 0) { margin = 0; }
  66969. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  66970. _this._margin = margin;
  66971. _this._root = _this;
  66972. return _this;
  66973. }
  66974. /**
  66975. * Add a rectangle, finding the best location to store it into the map
  66976. * @param size the dimension of the rectangle to store
  66977. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  66978. */
  66979. RectPackingMap.prototype.addRect = function (size) {
  66980. var node = this.findAndSplitNode(size);
  66981. return node;
  66982. };
  66983. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  66984. /**
  66985. * Return the current space free normalized between [0;1]
  66986. * @returns {}
  66987. */
  66988. get: function () {
  66989. var freeSize = 0;
  66990. freeSize = this.evalFreeSize(freeSize);
  66991. return freeSize / (this._size.width * this._size.height);
  66992. },
  66993. enumerable: true,
  66994. configurable: true
  66995. });
  66996. return RectPackingMap;
  66997. }(PackedRect));
  66998. BABYLON.RectPackingMap = RectPackingMap;
  66999. })(BABYLON || (BABYLON = {}));
  67000. //# sourceMappingURL=babylon.rectPackingMap.js.map
  67001. var BABYLON;
  67002. (function (BABYLON) {
  67003. /**
  67004. * This groups together the common properties used for image processing either in direct forward pass
  67005. * or through post processing effect depending on the use of the image processing pipeline in your scene
  67006. * or not.
  67007. */
  67008. var ImageProcessingConfiguration = (function () {
  67009. function ImageProcessingConfiguration() {
  67010. /**
  67011. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  67012. */
  67013. this.colorCurves = new BABYLON.ColorCurves();
  67014. this._colorCurvesEnabled = false;
  67015. this._colorGradingEnabled = false;
  67016. this._colorGradingWithGreenDepth = false;
  67017. this._colorGradingBGR = false;
  67018. this._exposure = 1.0;
  67019. this._toneMappingEnabled = false;
  67020. this._contrast = 1.0;
  67021. /**
  67022. * Vignette stretch size.
  67023. */
  67024. this.vignetteStretch = 0;
  67025. /**
  67026. * Vignette centre X Offset.
  67027. */
  67028. this.vignetteCentreX = 0;
  67029. /**
  67030. * Vignette centre Y Offset.
  67031. */
  67032. this.vignetteCentreY = 0;
  67033. /**
  67034. * Vignette weight or intensity of the vignette effect.
  67035. */
  67036. this.vignetteWeight = 1.5;
  67037. /**
  67038. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67039. * if vignetteEnabled is set to true.
  67040. */
  67041. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  67042. /**
  67043. * Camera field of view used by the Vignette effect.
  67044. */
  67045. this.vignetteCameraFov = 0.5;
  67046. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  67047. this._vignetteEnabled = false;
  67048. this._applyByPostProcess = false;
  67049. /**
  67050. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  67051. * @type {BABYLON.Observable}
  67052. */
  67053. this.onUpdateParameters = new BABYLON.Observable();
  67054. }
  67055. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  67056. /**
  67057. * Gets wether the color curves effect is enabled.
  67058. */
  67059. get: function () {
  67060. return this._colorCurvesEnabled;
  67061. },
  67062. /**
  67063. * Sets wether the color curves effect is enabled.
  67064. */
  67065. set: function (value) {
  67066. if (this._colorCurvesEnabled === value) {
  67067. return;
  67068. }
  67069. this._colorCurvesEnabled = value;
  67070. this._updateParameters();
  67071. },
  67072. enumerable: true,
  67073. configurable: true
  67074. });
  67075. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  67076. /**
  67077. * Gets wether the color grading effect is enabled.
  67078. */
  67079. get: function () {
  67080. return this._colorGradingEnabled;
  67081. },
  67082. /**
  67083. * Sets wether the color grading effect is enabled.
  67084. */
  67085. set: function (value) {
  67086. if (this._colorGradingEnabled === value) {
  67087. return;
  67088. }
  67089. this._colorGradingEnabled = value;
  67090. this._updateParameters();
  67091. },
  67092. enumerable: true,
  67093. configurable: true
  67094. });
  67095. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  67096. /**
  67097. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  67098. */
  67099. get: function () {
  67100. return this._colorGradingWithGreenDepth;
  67101. },
  67102. /**
  67103. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  67104. */
  67105. set: function (value) {
  67106. if (this._colorGradingWithGreenDepth === value) {
  67107. return;
  67108. }
  67109. this._colorGradingWithGreenDepth = value;
  67110. this._updateParameters();
  67111. },
  67112. enumerable: true,
  67113. configurable: true
  67114. });
  67115. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  67116. /**
  67117. * Gets wether the color grading texture contains BGR values.
  67118. */
  67119. get: function () {
  67120. return this._colorGradingBGR;
  67121. },
  67122. /**
  67123. * Sets wether the color grading texture contains BGR values.
  67124. */
  67125. set: function (value) {
  67126. if (this._colorGradingBGR === value) {
  67127. return;
  67128. }
  67129. this._colorGradingBGR = value;
  67130. this._updateParameters();
  67131. },
  67132. enumerable: true,
  67133. configurable: true
  67134. });
  67135. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  67136. /**
  67137. * Gets the Exposure used in the effect.
  67138. */
  67139. get: function () {
  67140. return this._exposure;
  67141. },
  67142. /**
  67143. * Sets the Exposure used in the effect.
  67144. */
  67145. set: function (value) {
  67146. if (this._exposure === value) {
  67147. return;
  67148. }
  67149. this._exposure = value;
  67150. this._updateParameters();
  67151. },
  67152. enumerable: true,
  67153. configurable: true
  67154. });
  67155. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  67156. /**
  67157. * Gets wether the tone mapping effect is enabled.
  67158. */
  67159. get: function () {
  67160. return this._toneMappingEnabled;
  67161. },
  67162. /**
  67163. * Sets wether the tone mapping effect is enabled.
  67164. */
  67165. set: function (value) {
  67166. if (this._toneMappingEnabled === value) {
  67167. return;
  67168. }
  67169. this._toneMappingEnabled = value;
  67170. this._updateParameters();
  67171. },
  67172. enumerable: true,
  67173. configurable: true
  67174. });
  67175. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  67176. /**
  67177. * Gets the contrast used in the effect.
  67178. */
  67179. get: function () {
  67180. return this._contrast;
  67181. },
  67182. /**
  67183. * Sets the contrast used in the effect.
  67184. */
  67185. set: function (value) {
  67186. if (this._contrast === value) {
  67187. return;
  67188. }
  67189. this._contrast = value;
  67190. this._updateParameters();
  67191. },
  67192. enumerable: true,
  67193. configurable: true
  67194. });
  67195. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  67196. /**
  67197. * Gets the vignette blend mode allowing different kind of effect.
  67198. */
  67199. get: function () {
  67200. return this._vignetteBlendMode;
  67201. },
  67202. /**
  67203. * Sets the vignette blend mode allowing different kind of effect.
  67204. */
  67205. set: function (value) {
  67206. if (this._vignetteBlendMode === value) {
  67207. return;
  67208. }
  67209. this._vignetteBlendMode = value;
  67210. this._updateParameters();
  67211. },
  67212. enumerable: true,
  67213. configurable: true
  67214. });
  67215. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  67216. /**
  67217. * Gets wether the vignette effect is enabled.
  67218. */
  67219. get: function () {
  67220. return this._vignetteEnabled;
  67221. },
  67222. /**
  67223. * Sets wether the vignette effect is enabled.
  67224. */
  67225. set: function (value) {
  67226. if (this._vignetteEnabled === value) {
  67227. return;
  67228. }
  67229. this._vignetteEnabled = value;
  67230. this._updateParameters();
  67231. },
  67232. enumerable: true,
  67233. configurable: true
  67234. });
  67235. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  67236. /**
  67237. * Gets wether the image processing is applied through a post process or not.
  67238. */
  67239. get: function () {
  67240. return this._applyByPostProcess;
  67241. },
  67242. /**
  67243. * Sets wether the image processing is applied through a post process or not.
  67244. */
  67245. set: function (value) {
  67246. if (this._applyByPostProcess === value) {
  67247. return;
  67248. }
  67249. this._applyByPostProcess = value;
  67250. this._updateParameters();
  67251. },
  67252. enumerable: true,
  67253. configurable: true
  67254. });
  67255. /**
  67256. * Method called each time the image processing information changes requires to recompile the effect.
  67257. */
  67258. ImageProcessingConfiguration.prototype._updateParameters = function () {
  67259. this.onUpdateParameters.notifyObservers(this);
  67260. };
  67261. /**
  67262. * Prepare the list of uniforms associated with the Image Processing effects.
  67263. * @param uniformsList The list of uniforms used in the effect
  67264. * @param defines the list of defines currently in use
  67265. */
  67266. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  67267. if (defines.EXPOSURE) {
  67268. uniforms.push("exposureLinear");
  67269. }
  67270. if (defines.CONTRAST) {
  67271. uniforms.push("contrast");
  67272. }
  67273. if (defines.COLORGRADING) {
  67274. uniforms.push("colorTransformSettings");
  67275. }
  67276. if (defines.VIGNETTE) {
  67277. uniforms.push("vInverseScreenSize");
  67278. uniforms.push("vignetteSettings1");
  67279. uniforms.push("vignetteSettings2");
  67280. }
  67281. if (defines.COLORCURVES) {
  67282. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  67283. }
  67284. };
  67285. /**
  67286. * Prepare the list of samplers associated with the Image Processing effects.
  67287. * @param uniformsList The list of uniforms used in the effect
  67288. * @param defines the list of defines currently in use
  67289. */
  67290. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  67291. if (defines.COLORGRADING) {
  67292. samplersList.push("txColorTransform");
  67293. }
  67294. };
  67295. /**
  67296. * Prepare the list of defines associated to the shader.
  67297. * @param defines the list of defines to complete
  67298. */
  67299. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  67300. defines.VIGNETTE = this.vignetteEnabled;
  67301. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  67302. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  67303. defines.TONEMAPPING = this.toneMappingEnabled;
  67304. defines.CONTRAST = (this.contrast !== 1.0);
  67305. defines.EXPOSURE = (this.exposure !== 1.0);
  67306. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  67307. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  67308. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  67309. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  67310. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  67311. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  67312. };
  67313. /**
  67314. * Returns true if all the image processing information are ready.
  67315. */
  67316. ImageProcessingConfiguration.prototype.isReady = function () {
  67317. // Color Grading texure can not be none blocking.
  67318. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  67319. };
  67320. /**
  67321. * Binds the image processing to the shader.
  67322. * @param effect The effect to bind to
  67323. */
  67324. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  67325. if (aspectRatio === void 0) { aspectRatio = 1; }
  67326. // Color Curves
  67327. if (this._colorCurvesEnabled) {
  67328. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  67329. }
  67330. // Vignette
  67331. if (this._vignetteEnabled) {
  67332. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  67333. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  67334. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  67335. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  67336. var vignetteScaleX = vignetteScaleY * aspectRatio;
  67337. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  67338. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  67339. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  67340. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  67341. var vignettePower = -2.0 * this.vignetteWeight;
  67342. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  67343. }
  67344. // Exposure
  67345. effect.setFloat("exposureLinear", this.exposure);
  67346. // Contrast
  67347. effect.setFloat("contrast", this.contrast);
  67348. // Color transform settings
  67349. if (this.colorGradingTexture) {
  67350. effect.setTexture("txColorTransform", this.colorGradingTexture);
  67351. var textureSize = this.colorGradingTexture.getSize().height;
  67352. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  67353. 0.5 / textureSize, // textureOffset
  67354. textureSize, // textureSize
  67355. this.colorGradingTexture.level // weight
  67356. );
  67357. }
  67358. };
  67359. /**
  67360. * Clones the current image processing instance.
  67361. * @return The cloned image processing
  67362. */
  67363. ImageProcessingConfiguration.prototype.clone = function () {
  67364. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  67365. };
  67366. /**
  67367. * Serializes the current image processing instance to a json representation.
  67368. * @return a JSON representation
  67369. */
  67370. ImageProcessingConfiguration.prototype.serialize = function () {
  67371. return BABYLON.SerializationHelper.Serialize(this);
  67372. };
  67373. /**
  67374. * Parses the image processing from a json representation.
  67375. * @param source the JSON source to parse
  67376. * @return The parsed image processing
  67377. */
  67378. ImageProcessingConfiguration.Parse = function (source) {
  67379. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  67380. };
  67381. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  67382. /**
  67383. * Used to apply the vignette as a mix with the pixel color.
  67384. */
  67385. get: function () {
  67386. return this._VIGNETTEMODE_MULTIPLY;
  67387. },
  67388. enumerable: true,
  67389. configurable: true
  67390. });
  67391. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  67392. /**
  67393. * Used to apply the vignette as a replacement of the pixel color.
  67394. */
  67395. get: function () {
  67396. return this._VIGNETTEMODE_OPAQUE;
  67397. },
  67398. enumerable: true,
  67399. configurable: true
  67400. });
  67401. return ImageProcessingConfiguration;
  67402. }());
  67403. // Static constants associated to the image processing.
  67404. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  67405. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  67406. __decorate([
  67407. BABYLON.serializeAsColorCurves()
  67408. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  67409. __decorate([
  67410. BABYLON.serialize()
  67411. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  67412. __decorate([
  67413. BABYLON.serializeAsTexture()
  67414. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  67415. __decorate([
  67416. BABYLON.serialize()
  67417. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  67418. __decorate([
  67419. BABYLON.serialize()
  67420. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  67421. __decorate([
  67422. BABYLON.serialize()
  67423. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  67424. __decorate([
  67425. BABYLON.serialize()
  67426. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  67427. __decorate([
  67428. BABYLON.serialize()
  67429. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  67430. __decorate([
  67431. BABYLON.serialize()
  67432. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  67433. __decorate([
  67434. BABYLON.serialize()
  67435. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  67436. __decorate([
  67437. BABYLON.serialize()
  67438. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  67439. __decorate([
  67440. BABYLON.serialize()
  67441. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  67442. __decorate([
  67443. BABYLON.serialize()
  67444. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  67445. __decorate([
  67446. BABYLON.serializeAsColor4()
  67447. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  67448. __decorate([
  67449. BABYLON.serialize()
  67450. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  67451. __decorate([
  67452. BABYLON.serialize()
  67453. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  67454. __decorate([
  67455. BABYLON.serialize()
  67456. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  67457. __decorate([
  67458. BABYLON.serialize()
  67459. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  67460. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  67461. })(BABYLON || (BABYLON = {}));
  67462. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  67463. var BABYLON;
  67464. (function (BABYLON) {
  67465. var serializedGeometries = [];
  67466. var serializeGeometry = function (geometry, serializationGeometries) {
  67467. if (serializedGeometries[geometry.id]) {
  67468. return;
  67469. }
  67470. if (geometry.doNotSerialize) {
  67471. return;
  67472. }
  67473. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  67474. serializationGeometries.boxes.push(geometry.serialize());
  67475. }
  67476. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  67477. serializationGeometries.spheres.push(geometry.serialize());
  67478. }
  67479. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  67480. serializationGeometries.cylinders.push(geometry.serialize());
  67481. }
  67482. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  67483. serializationGeometries.toruses.push(geometry.serialize());
  67484. }
  67485. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  67486. serializationGeometries.grounds.push(geometry.serialize());
  67487. }
  67488. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  67489. serializationGeometries.planes.push(geometry.serialize());
  67490. }
  67491. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  67492. serializationGeometries.torusKnots.push(geometry.serialize());
  67493. }
  67494. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  67495. throw new Error("Unknown primitive type");
  67496. }
  67497. else {
  67498. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  67499. }
  67500. serializedGeometries[geometry.id] = true;
  67501. };
  67502. var serializeMesh = function (mesh, serializationScene) {
  67503. var serializationObject = {};
  67504. // Geometry
  67505. var geometry = mesh._geometry;
  67506. if (geometry) {
  67507. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  67508. // 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
  67509. serializeGeometry(geometry, serializationScene.geometries);
  67510. }
  67511. }
  67512. // Custom
  67513. if (mesh.serialize) {
  67514. mesh.serialize(serializationObject);
  67515. }
  67516. return serializationObject;
  67517. };
  67518. var finalizeSingleMesh = function (mesh, serializationObject) {
  67519. //only works if the mesh is already loaded
  67520. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  67521. //serialize material
  67522. if (mesh.material) {
  67523. if (mesh.material instanceof BABYLON.StandardMaterial) {
  67524. serializationObject.materials = serializationObject.materials || [];
  67525. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  67526. serializationObject.materials.push(mesh.material.serialize());
  67527. }
  67528. }
  67529. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  67530. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  67531. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  67532. serializationObject.multiMaterials.push(mesh.material.serialize());
  67533. }
  67534. }
  67535. }
  67536. //serialize geometry
  67537. var geometry = mesh._geometry;
  67538. if (geometry) {
  67539. if (!serializationObject.geometries) {
  67540. serializationObject.geometries = {};
  67541. serializationObject.geometries.boxes = [];
  67542. serializationObject.geometries.spheres = [];
  67543. serializationObject.geometries.cylinders = [];
  67544. serializationObject.geometries.toruses = [];
  67545. serializationObject.geometries.grounds = [];
  67546. serializationObject.geometries.planes = [];
  67547. serializationObject.geometries.torusKnots = [];
  67548. serializationObject.geometries.vertexData = [];
  67549. }
  67550. serializeGeometry(geometry, serializationObject.geometries);
  67551. }
  67552. // Skeletons
  67553. if (mesh.skeleton) {
  67554. serializationObject.skeletons = serializationObject.skeletons || [];
  67555. serializationObject.skeletons.push(mesh.skeleton.serialize());
  67556. }
  67557. //serialize the actual mesh
  67558. serializationObject.meshes = serializationObject.meshes || [];
  67559. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  67560. }
  67561. };
  67562. var SceneSerializer = (function () {
  67563. function SceneSerializer() {
  67564. }
  67565. SceneSerializer.ClearCache = function () {
  67566. serializedGeometries = [];
  67567. };
  67568. SceneSerializer.Serialize = function (scene) {
  67569. var serializationObject = {};
  67570. SceneSerializer.ClearCache();
  67571. // Scene
  67572. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  67573. serializationObject.autoClear = scene.autoClear;
  67574. serializationObject.clearColor = scene.clearColor.asArray();
  67575. serializationObject.ambientColor = scene.ambientColor.asArray();
  67576. serializationObject.gravity = scene.gravity.asArray();
  67577. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  67578. serializationObject.workerCollisions = scene.workerCollisions;
  67579. // Fog
  67580. if (scene.fogMode && scene.fogMode !== 0) {
  67581. serializationObject.fogMode = scene.fogMode;
  67582. serializationObject.fogColor = scene.fogColor.asArray();
  67583. serializationObject.fogStart = scene.fogStart;
  67584. serializationObject.fogEnd = scene.fogEnd;
  67585. serializationObject.fogDensity = scene.fogDensity;
  67586. }
  67587. //Physics
  67588. if (scene.isPhysicsEnabled()) {
  67589. serializationObject.physicsEnabled = true;
  67590. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  67591. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  67592. }
  67593. // Metadata
  67594. if (scene.metadata) {
  67595. serializationObject.metadata = scene.metadata;
  67596. }
  67597. // Morph targets
  67598. serializationObject.morphTargetManagers = [];
  67599. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  67600. var abstractMesh = _a[_i];
  67601. var manager = abstractMesh.morphTargetManager;
  67602. if (manager) {
  67603. serializationObject.morphTargetManagers.push(manager.serialize());
  67604. }
  67605. }
  67606. // Lights
  67607. serializationObject.lights = [];
  67608. var index;
  67609. var light;
  67610. for (index = 0; index < scene.lights.length; index++) {
  67611. light = scene.lights[index];
  67612. if (!light.doNotSerialize) {
  67613. serializationObject.lights.push(light.serialize());
  67614. }
  67615. }
  67616. // Cameras
  67617. serializationObject.cameras = [];
  67618. for (index = 0; index < scene.cameras.length; index++) {
  67619. var camera = scene.cameras[index];
  67620. if (!camera.doNotSerialize) {
  67621. serializationObject.cameras.push(camera.serialize());
  67622. }
  67623. }
  67624. if (scene.activeCamera) {
  67625. serializationObject.activeCameraID = scene.activeCamera.id;
  67626. }
  67627. // Animations
  67628. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  67629. // Materials
  67630. serializationObject.materials = [];
  67631. serializationObject.multiMaterials = [];
  67632. var material;
  67633. for (index = 0; index < scene.materials.length; index++) {
  67634. material = scene.materials[index];
  67635. if (!material.doNotSerialize) {
  67636. serializationObject.materials.push(material.serialize());
  67637. }
  67638. }
  67639. // MultiMaterials
  67640. serializationObject.multiMaterials = [];
  67641. for (index = 0; index < scene.multiMaterials.length; index++) {
  67642. var multiMaterial = scene.multiMaterials[index];
  67643. serializationObject.multiMaterials.push(multiMaterial.serialize());
  67644. }
  67645. // Skeletons
  67646. serializationObject.skeletons = [];
  67647. for (index = 0; index < scene.skeletons.length; index++) {
  67648. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  67649. }
  67650. // Geometries
  67651. serializationObject.geometries = {};
  67652. serializationObject.geometries.boxes = [];
  67653. serializationObject.geometries.spheres = [];
  67654. serializationObject.geometries.cylinders = [];
  67655. serializationObject.geometries.toruses = [];
  67656. serializationObject.geometries.grounds = [];
  67657. serializationObject.geometries.planes = [];
  67658. serializationObject.geometries.torusKnots = [];
  67659. serializationObject.geometries.vertexData = [];
  67660. serializedGeometries = [];
  67661. var geometries = scene.getGeometries();
  67662. for (index = 0; index < geometries.length; index++) {
  67663. var geometry = geometries[index];
  67664. if (geometry.isReady()) {
  67665. serializeGeometry(geometry, serializationObject.geometries);
  67666. }
  67667. }
  67668. // Meshes
  67669. serializationObject.meshes = [];
  67670. for (index = 0; index < scene.meshes.length; index++) {
  67671. var abstractMesh = scene.meshes[index];
  67672. if (abstractMesh instanceof BABYLON.Mesh) {
  67673. var mesh = abstractMesh;
  67674. if (!mesh.doNotSerialize) {
  67675. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  67676. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  67677. }
  67678. }
  67679. }
  67680. }
  67681. // Particles Systems
  67682. serializationObject.particleSystems = [];
  67683. for (index = 0; index < scene.particleSystems.length; index++) {
  67684. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  67685. }
  67686. // Lens flares
  67687. serializationObject.lensFlareSystems = [];
  67688. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  67689. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  67690. }
  67691. // Shadows
  67692. serializationObject.shadowGenerators = [];
  67693. for (index = 0; index < scene.lights.length; index++) {
  67694. light = scene.lights[index];
  67695. var shadowGenerator = light.getShadowGenerator();
  67696. if (shadowGenerator) {
  67697. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  67698. }
  67699. }
  67700. // Action Manager
  67701. if (scene.actionManager) {
  67702. serializationObject.actions = scene.actionManager.serialize("scene");
  67703. }
  67704. // Audio
  67705. serializationObject.sounds = [];
  67706. for (index = 0; index < scene.soundTracks.length; index++) {
  67707. var soundtrack = scene.soundTracks[index];
  67708. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  67709. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  67710. }
  67711. }
  67712. return serializationObject;
  67713. };
  67714. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  67715. if (withParents === void 0) { withParents = false; }
  67716. if (withChildren === void 0) { withChildren = false; }
  67717. var serializationObject = {};
  67718. SceneSerializer.ClearCache();
  67719. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  67720. if (withParents || withChildren) {
  67721. //deliberate for loop! not for each, appended should be processed as well.
  67722. for (var i = 0; i < toSerialize.length; ++i) {
  67723. if (withChildren) {
  67724. toSerialize[i].getDescendants().forEach(function (node) {
  67725. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  67726. toSerialize.push(node);
  67727. }
  67728. });
  67729. }
  67730. //make sure the array doesn't contain the object already
  67731. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  67732. toSerialize.push(toSerialize[i].parent);
  67733. }
  67734. }
  67735. }
  67736. toSerialize.forEach(function (mesh) {
  67737. finalizeSingleMesh(mesh, serializationObject);
  67738. });
  67739. return serializationObject;
  67740. };
  67741. return SceneSerializer;
  67742. }());
  67743. BABYLON.SceneSerializer = SceneSerializer;
  67744. })(BABYLON || (BABYLON = {}));
  67745. //# sourceMappingURL=babylon.sceneSerializer.js.map
  67746. var BABYLON;
  67747. (function (BABYLON) {
  67748. var ReflectionProbe = (function () {
  67749. function ReflectionProbe(name, size, scene, generateMipMaps) {
  67750. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67751. var _this = this;
  67752. this.name = name;
  67753. this._viewMatrix = BABYLON.Matrix.Identity();
  67754. this._target = BABYLON.Vector3.Zero();
  67755. this._add = BABYLON.Vector3.Zero();
  67756. this.invertYAxis = false;
  67757. this.position = BABYLON.Vector3.Zero();
  67758. this._scene = scene;
  67759. this._scene.reflectionProbes.push(this);
  67760. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  67761. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  67762. switch (faceIndex) {
  67763. case 0:
  67764. _this._add.copyFromFloats(1, 0, 0);
  67765. break;
  67766. case 1:
  67767. _this._add.copyFromFloats(-1, 0, 0);
  67768. break;
  67769. case 2:
  67770. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  67771. break;
  67772. case 3:
  67773. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  67774. break;
  67775. case 4:
  67776. _this._add.copyFromFloats(0, 0, 1);
  67777. break;
  67778. case 5:
  67779. _this._add.copyFromFloats(0, 0, -1);
  67780. break;
  67781. }
  67782. if (_this._attachedMesh) {
  67783. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  67784. }
  67785. _this.position.addToRef(_this._add, _this._target);
  67786. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  67787. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  67788. });
  67789. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  67790. scene.updateTransformMatrix(true);
  67791. });
  67792. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  67793. }
  67794. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  67795. get: function () {
  67796. return this._renderTargetTexture.samples;
  67797. },
  67798. set: function (value) {
  67799. this._renderTargetTexture.samples = value;
  67800. },
  67801. enumerable: true,
  67802. configurable: true
  67803. });
  67804. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  67805. get: function () {
  67806. return this._renderTargetTexture.refreshRate;
  67807. },
  67808. set: function (value) {
  67809. this._renderTargetTexture.refreshRate = value;
  67810. },
  67811. enumerable: true,
  67812. configurable: true
  67813. });
  67814. ReflectionProbe.prototype.getScene = function () {
  67815. return this._scene;
  67816. };
  67817. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  67818. get: function () {
  67819. return this._renderTargetTexture;
  67820. },
  67821. enumerable: true,
  67822. configurable: true
  67823. });
  67824. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  67825. get: function () {
  67826. return this._renderTargetTexture.renderList;
  67827. },
  67828. enumerable: true,
  67829. configurable: true
  67830. });
  67831. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  67832. this._attachedMesh = mesh;
  67833. };
  67834. /**
  67835. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67836. *
  67837. * @param renderingGroupId The rendering group id corresponding to its index
  67838. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67839. */
  67840. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67841. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67842. };
  67843. ReflectionProbe.prototype.dispose = function () {
  67844. var index = this._scene.reflectionProbes.indexOf(this);
  67845. if (index !== -1) {
  67846. // Remove from the scene if found
  67847. this._scene.reflectionProbes.splice(index, 1);
  67848. }
  67849. if (this._renderTargetTexture) {
  67850. this._renderTargetTexture.dispose();
  67851. this._renderTargetTexture = null;
  67852. }
  67853. };
  67854. return ReflectionProbe;
  67855. }());
  67856. BABYLON.ReflectionProbe = ReflectionProbe;
  67857. })(BABYLON || (BABYLON = {}));
  67858. //# sourceMappingURL=babylon.reflectionProbe.js.map
  67859. var BABYLON;
  67860. (function (BABYLON) {
  67861. var Layer = (function () {
  67862. function Layer(name, imgUrl, scene, isBackground, color) {
  67863. this.name = name;
  67864. this.scale = new BABYLON.Vector2(1, 1);
  67865. this.offset = new BABYLON.Vector2(0, 0);
  67866. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  67867. this.layerMask = 0x0FFFFFFF;
  67868. this._vertexBuffers = {};
  67869. // Events
  67870. /**
  67871. * An event triggered when the layer is disposed.
  67872. * @type {BABYLON.Observable}
  67873. */
  67874. this.onDisposeObservable = new BABYLON.Observable();
  67875. /**
  67876. * An event triggered before rendering the scene
  67877. * @type {BABYLON.Observable}
  67878. */
  67879. this.onBeforeRenderObservable = new BABYLON.Observable();
  67880. /**
  67881. * An event triggered after rendering the scene
  67882. * @type {BABYLON.Observable}
  67883. */
  67884. this.onAfterRenderObservable = new BABYLON.Observable();
  67885. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  67886. this.isBackground = isBackground === undefined ? true : isBackground;
  67887. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  67888. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67889. this._scene.layers.push(this);
  67890. var engine = this._scene.getEngine();
  67891. // VBO
  67892. var vertices = [];
  67893. vertices.push(1, 1);
  67894. vertices.push(-1, 1);
  67895. vertices.push(-1, -1);
  67896. vertices.push(1, -1);
  67897. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67898. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  67899. // Indices
  67900. var indices = [];
  67901. indices.push(0);
  67902. indices.push(1);
  67903. indices.push(2);
  67904. indices.push(0);
  67905. indices.push(2);
  67906. indices.push(3);
  67907. this._indexBuffer = engine.createIndexBuffer(indices);
  67908. // Effects
  67909. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  67910. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  67911. }
  67912. Object.defineProperty(Layer.prototype, "onDispose", {
  67913. set: function (callback) {
  67914. if (this._onDisposeObserver) {
  67915. this.onDisposeObservable.remove(this._onDisposeObserver);
  67916. }
  67917. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  67918. },
  67919. enumerable: true,
  67920. configurable: true
  67921. });
  67922. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  67923. set: function (callback) {
  67924. if (this._onBeforeRenderObserver) {
  67925. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67926. }
  67927. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67928. },
  67929. enumerable: true,
  67930. configurable: true
  67931. });
  67932. Object.defineProperty(Layer.prototype, "onAfterRender", {
  67933. set: function (callback) {
  67934. if (this._onAfterRenderObserver) {
  67935. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67936. }
  67937. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67938. },
  67939. enumerable: true,
  67940. configurable: true
  67941. });
  67942. Layer.prototype.render = function () {
  67943. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  67944. // Check
  67945. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  67946. return;
  67947. var engine = this._scene.getEngine();
  67948. this.onBeforeRenderObservable.notifyObservers(this);
  67949. // Render
  67950. engine.enableEffect(currentEffect);
  67951. engine.setState(false);
  67952. // Texture
  67953. currentEffect.setTexture("textureSampler", this.texture);
  67954. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  67955. // Color
  67956. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  67957. // Scale / offset
  67958. currentEffect.setVector2("offset", this.offset);
  67959. currentEffect.setVector2("scale", this.scale);
  67960. // VBOs
  67961. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  67962. // Draw order
  67963. if (!this.alphaTest) {
  67964. engine.setAlphaMode(this.alphaBlendingMode);
  67965. engine.draw(true, 0, 6);
  67966. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67967. }
  67968. else {
  67969. engine.draw(true, 0, 6);
  67970. }
  67971. this.onAfterRenderObservable.notifyObservers(this);
  67972. };
  67973. Layer.prototype.dispose = function () {
  67974. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67975. if (vertexBuffer) {
  67976. vertexBuffer.dispose();
  67977. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67978. }
  67979. if (this._indexBuffer) {
  67980. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67981. this._indexBuffer = null;
  67982. }
  67983. if (this.texture) {
  67984. this.texture.dispose();
  67985. this.texture = null;
  67986. }
  67987. // Remove from scene
  67988. var index = this._scene.layers.indexOf(this);
  67989. this._scene.layers.splice(index, 1);
  67990. // Callback
  67991. this.onDisposeObservable.notifyObservers(this);
  67992. this.onDisposeObservable.clear();
  67993. this.onAfterRenderObservable.clear();
  67994. this.onBeforeRenderObservable.clear();
  67995. };
  67996. return Layer;
  67997. }());
  67998. BABYLON.Layer = Layer;
  67999. })(BABYLON || (BABYLON = {}));
  68000. //# sourceMappingURL=babylon.layer.js.map
  68001. var BABYLON;
  68002. (function (BABYLON) {
  68003. var TextureTools = (function () {
  68004. function TextureTools() {
  68005. }
  68006. /**
  68007. * Uses the GPU to create a copy texture rescaled at a given size
  68008. * @param texture Texture to copy from
  68009. * @param width Desired width
  68010. * @param height Desired height
  68011. * @return Generated texture
  68012. */
  68013. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  68014. if (useBilinearMode === void 0) { useBilinearMode = true; }
  68015. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  68016. var scene = texture.getScene();
  68017. var engine = scene.getEngine();
  68018. rtt.wrapU = texture.wrapU;
  68019. rtt.wrapV = texture.wrapV;
  68020. rtt.uOffset = texture.uOffset;
  68021. rtt.vOffset = texture.vOffset;
  68022. rtt.uScale = texture.uScale;
  68023. rtt.vScale = texture.vScale;
  68024. rtt.uAng = texture.uAng;
  68025. rtt.vAng = texture.vAng;
  68026. rtt.wAng = texture.wAng;
  68027. rtt.coordinatesIndex = texture.coordinatesIndex;
  68028. rtt.level = texture.level;
  68029. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  68030. rtt._texture.isReady = false;
  68031. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68032. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68033. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68034. passPostProcess.getEffect().executeWhenCompiled(function () {
  68035. passPostProcess.onApply = function (effect) {
  68036. effect.setTexture("textureSampler", texture);
  68037. };
  68038. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  68039. engine.unBindFramebuffer(rtt.getInternalTexture());
  68040. rtt.disposeFramebufferObjects();
  68041. passPostProcess.dispose();
  68042. rtt._texture.isReady = true;
  68043. });
  68044. return rtt;
  68045. };
  68046. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  68047. if (!scene._environmentBRDFTexture) {
  68048. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68049. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68050. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68051. scene._environmentBRDFTexture = texture;
  68052. }
  68053. return scene._environmentBRDFTexture;
  68054. };
  68055. return TextureTools;
  68056. }());
  68057. 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=";
  68058. BABYLON.TextureTools = TextureTools;
  68059. })(BABYLON || (BABYLON = {}));
  68060. //# sourceMappingURL=babylon.textureTools.js.map
  68061. 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)\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 vec3 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-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#ifdef BUMP\nvec3 originalNormalW=normalW;\n#endif\n#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#ifdef BUMP\noriginalNormalW=gl_FrontFacing ? originalNormalW : -originalNormalW;;\n#endif\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 texture,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(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,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}"};
  68062. 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,1.0-frustumEdgeFalloff,dot(clipSpace,clipSpace));\nreturn mix(1.0,value,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;\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; \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);\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;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\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;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\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\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\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;\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 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 lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\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>=lightAngle)\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};"};
  68063. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  68064. module.exports = BABYLON;
  68065. };